├── objective c └── README.txt ├── python ├── Chapter 2 │ ├── classes │ │ ├── __init__.py │ │ └── __init__.pyc │ ├── deletenode.py │ ├── Question2_3.py │ ├── Question2_4.py │ ├── Question2_2.py │ ├── kthlast.py │ ├── removeduplicates.py │ ├── Question2_1.py │ └── Question2_6.py ├── Chapter 1 │ ├── Question1_2 │ │ ├── revstr.py │ │ └── ChapQ1.2.py │ ├── Question1_4 │ │ ├── replace.py │ │ └── Q1_4.py │ ├── Question1_3 │ │ ├── anagram.py │ │ └── testanagram.py │ ├── Question1_5 │ │ ├── compress.py │ │ └── testcompress.py │ ├── Question1_8 │ │ ├── rotation.py │ │ ├── ChapQ1.8.py │ │ └── testRotation.py │ ├── Question1_1 │ │ └── alluniq.py │ ├── Question1_7 │ │ └── tozeros.py │ └── Question1_6 │ │ ├── rotateimg.py │ │ └── testrotate.py ├── Chapter 4 │ ├── Question4_7 │ │ └── BinaryTreeNode.py │ ├── Question4_9 │ │ └── BinaryTreeNode.py │ └── Question4_3 │ │ └── ChapQ4.3.py └── Chapter 3 │ ├── Question3_6 │ └── ChapQ3.6.py │ ├── Question3_5 │ └── ChapQ3.5.py │ └── Question3_4 │ └── Q3_4.py ├── .DS_Store ├── java ├── Chapter 8 │ ├── Question8_3 │ │ ├── CD.java │ │ ├── Song.java │ │ ├── SongSelector.java │ │ ├── Playlist.java │ │ ├── User.java │ │ ├── CDPlayer.java │ │ └── JukeBox.java │ ├── Question8_7 │ │ ├── System.java │ │ ├── RequestStatus.java │ │ ├── UserStatusType.java │ │ ├── GroupChat.java │ │ ├── Message.java │ │ ├── UserStatus.java │ │ ├── PrivateChat.java │ │ ├── Conversation.java │ │ └── AddRequest.java │ ├── Question8_8 │ │ ├── Color.java │ │ ├── Direction.java │ │ ├── Piece.java │ │ ├── Location.java │ │ ├── Player.java │ │ ├── Question.java │ │ └── Game.java │ ├── Question8_2 │ │ ├── CallHandler.java │ │ ├── Manager.java │ │ ├── Director.java │ │ ├── Respondent.java │ │ ├── Caller.java │ │ ├── Test.java │ │ ├── Rank.java │ │ └── Call.java │ ├── Question8_4 │ │ ├── VehicleSize.java │ │ ├── Motorcycle.java │ │ ├── Bus.java │ │ ├── Car.java │ │ ├── Question.java │ │ ├── ParkingLot.java │ │ └── Vehicle.java │ ├── Question8_10 │ │ ├── Dummy.java │ │ ├── Cell.java │ │ └── Question.java │ ├── Question8_9 │ │ ├── File.java │ │ ├── Directory.java │ │ ├── Entry.java │ │ └── Question.java │ ├── Question8_1 │ │ ├── Hand.java │ │ ├── Suit.java │ │ └── BlackJackCard.java │ └── Question8_5 │ │ ├── Book.java │ │ ├── Library.java │ │ ├── UserManager.java │ │ ├── User.java │ │ ├── Display.java │ │ └── OnlineReaderSystem.java ├── Chapter 5 │ ├── Question5_7.zip │ ├── Question5_1 │ │ └── Question.java │ ├── Question5_6 │ │ └── Question.java │ └── Question5_5 │ │ └── Question.java ├── Chapter 7 │ ├── Question7_6 │ │ ├── Line.java │ │ └── GraphPoint.java │ ├── Question7_5 │ │ ├── Square.java │ │ ├── Square Cut Tester - Chapter 10, Problem 5.xlsx │ │ ├── Line.java │ │ └── Point.java │ ├── Question7_3 │ │ ├── Line.java │ │ └── Question.java │ ├── Introduction │ │ └── PrimeNumbers.java │ └── Question7_7 │ │ └── QuestionA.java ├── Chapter 11 │ ├── Question11_6 │ │ ├── .DS_Store │ │ ├── Coordinate.java │ │ └── QuestionA.java │ ├── Question11_7 │ │ └── HtWt.java │ ├── Question11_8 │ │ ├── IntComparable.java │ │ └── RankNode.java │ └── Question11_2 │ │ ├── AnagramComparator.java │ │ └── Question.java ├── Chapter 1 │ ├── Question1_3 │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question1_8 │ │ └── Question.java │ ├── Question1_1 │ │ └── Question.java │ ├── Question1_6 │ │ └── Question.java │ └── Question1_4 │ │ └── Question.java ├── Chapter 2 │ ├── Question2_1 │ │ └── Question.java │ ├── Question2_2 │ │ ├── IntWrapper.java │ │ └── Result.java │ ├── Question2_5 │ │ └── PartialSum.java │ └── Question2_3 │ │ └── Question.java ├── Chapter 4 │ ├── Question4_6 │ │ └── Question.java │ ├── Question4_7 │ │ ├── Question.java │ │ └── QuestionC.java │ ├── Question4_8 │ │ └── Question.java │ ├── Question4_5 │ │ ├── IntWrapper.java │ │ └── Question.java │ ├── Question4_2 │ │ ├── Graph.java │ │ └── Node.java │ ├── Question4_3 │ │ └── Question.java │ └── Question4_1 │ │ └── QuestionImproved.java ├── Chapter 9 │ ├── Question9_6 │ │ └── QuestionB.java │ ├── Question9_10 │ │ └── Box.java │ ├── Introduction │ │ ├── Fibonacci.java │ │ └── FibonacciFB.java │ └── Question9_5 │ │ └── Question.java ├── Chapter 10 │ ├── Question10_3 │ │ └── QuestionB.java │ ├── Question10_7 │ │ ├── Node.java │ │ └── Question.java │ ├── Question10_2 │ │ ├── Machine.java │ │ ├── Person.java │ │ └── Server.java │ └── Question10_4 │ │ ├── BitSet.java │ │ └── Question.java ├── Chapter 18 │ ├── Question18_1 │ │ └── Question.java │ ├── Question18_3 │ │ └── Question.java │ ├── Question18_9 │ │ ├── Question.java │ │ ├── MinHeapComparator.java │ │ └── MaxHeapComparator.java │ ├── Question18_6 │ │ └── Parts.java │ ├── Question18_7 │ │ └── LengthComparator.java │ ├── Question18_11 │ │ ├── Subsquare.java │ │ └── SquareCell.java │ ├── Question18_8 │ │ ├── SuffixTree.java │ │ ├── Question.java │ │ └── SuffixTreeNode.java │ └── Question18_4 │ │ └── QuestionBrute.java ├── CtCILibrary │ └── CtCILibrary │ │ ├── AssortedMethods.java │ │ └── LinkedListNode.java ├── Chapter 14 │ ├── Introduction │ │ ├── Ambiguous.java │ │ ├── Shape.java │ │ ├── Square.java │ │ ├── Circle.java │ │ ├── IntroductionOverriding.java │ │ ├── Introduction.java │ │ └── IntroductionCollections.java │ ├── Question14_5 │ │ └── Rectangle.java │ └── Question14_6 │ │ └── Question.java ├── Chapter 17 │ ├── Question17_13 │ │ └── BiNode.java │ ├── Question17_14 │ │ └── Result.java │ ├── Question17_8 │ │ └── Question.java │ ├── Question17_10 │ │ ├── Attribute.java │ │ └── Element.java │ ├── Question17_12 │ │ └── Question.java │ ├── Question17_2 │ │ └── Question.java │ ├── Question17_11 │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question17_1 │ │ └── Question.java │ └── Question17_3 │ │ ├── QuestionB.java │ │ └── QuestionA.java ├── Chapter 3 │ ├── Question3_3 │ │ ├── Node.java │ │ ├── Question.java │ │ └── Stack.java │ ├── Question3_7 │ │ ├── Dog.java │ │ ├── Cat.java │ │ ├── Animal.java │ │ └── Question.java │ ├── Question3_2 │ │ ├── NodeWithMin.java │ │ ├── StackWithMin.java │ │ ├── StackWithMin2.java │ │ └── Question.java │ ├── Question3_4 │ │ └── Question.java │ ├── Question3_1 │ │ └── StackData.java │ └── Question3_5 │ │ └── MyQueue.java ├── Chapter 16 │ ├── IntroductionSynchronizedBlocks │ │ ├── MyClass.java │ │ ├── MyObject.java │ │ └── Intro.java │ ├── IntroductionB │ │ ├── ExampleB.java │ │ └── ThreadExample.java │ ├── IntroductionWaitNotify │ │ ├── MyObject.java │ │ ├── MyClass.java │ │ └── Intro.java │ ├── Question16_3 │ │ ├── Chopstick.java │ │ └── Question.java │ ├── Question16_6 │ │ ├── MyThread.java │ │ └── Foo.java │ ├── IntroductionSynchronization │ │ ├── MyClass.java │ │ ├── Intro.java │ │ └── MyObject.java │ ├── Question16_5 │ │ ├── MyThread.java │ │ └── Question.java │ ├── IntroductionA │ │ ├── RunnableThreadExample.java │ │ └── ExampleA.java │ ├── Question16_4 │ │ └── Question.java │ └── IntroductionLocks │ │ ├── NoLockATM.java │ │ ├── Intro.java │ │ ├── LockedATM.java │ │ └── MyClass.java ├── .project ├── .classpath └── Introduction │ └── CompareBinaryToHex │ └── CompareBinaryToHex.java ├── README.md ├── dart ├── Chapter17 │ ├── Question17_13 │ │ └── bi_node.dart │ ├── Question17_8 │ │ └── question.dart │ ├── Question17_1 │ │ └── question.dart │ ├── Question17_12 │ │ └── question.dart │ ├── Question17_3 │ │ ├── questionB.dart │ │ └── questionA.dart │ ├── Question17_11 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question17_2 │ │ └── question.dart │ └── Question17_9 │ │ └── question.dart ├── Chapter18 │ ├── Question18_11 │ │ ├── square_cell.dart │ │ └── subsquare.dart │ ├── Question18_2 │ │ └── question.dart │ ├── Question18_4 │ │ └── questionBrute.dart │ ├── Question18_1 │ │ └── question.dart │ └── Question18_3 │ │ └── question.dart ├── Chapter5 │ ├── Question5_6 │ │ └── question.dart │ ├── Question5_5 │ │ └── question.dart │ └── Question5_1 │ │ └── question.dart ├── Chapter4 │ ├── Question4_3 │ │ └── question.dart │ ├── Question4_5 │ │ └── question.dart │ ├── Question4_7 │ │ └── question_c_bad.dart │ ├── Question4_6 │ │ └── question.dart │ └── Question4_1 │ │ ├── question_brute.dart │ │ └── question_improved.dart ├── Chapter8 │ └── Question8_1 │ │ ├── hand.dart │ │ ├── suit.dart │ │ ├── black_jack_card.dart │ │ └── card.dart ├── README.md ├── Chapter11 │ ├── Question11_2 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question11_6 │ │ └── question.dart │ └── Question11_1 │ │ └── question.dart ├── Chapter7 │ ├── Introduction │ │ └── prime_numbers.dart │ ├── Question7_3 │ │ └── question.dart │ └── Question7_7 │ │ └── questionA.dart ├── Chapter3 │ └── Question3_6 │ │ └── question.dart ├── Chapter9 │ ├── Question9_8 │ │ └── question.dart │ ├── Introduction │ │ ├── fibonacci.dart │ │ └── fibonacci_fb.dart │ ├── Question9_5 │ │ └── question.dart │ ├── Question9_6 │ │ ├── questionB.dart │ │ └── questionA.dart │ └── Question9_1 │ │ └── question.dart ├── Chapter1 │ ├── Question1_2 │ │ └── question.dart │ ├── Question1_3 │ │ └── question.dart │ ├── Question1_6 │ │ └── question.dart │ ├── Question1_8 │ │ └── question.dart │ └── Question1_7 │ │ └── question.dart ├── Chapter2 │ └── Question2_3 │ │ └── question.dart └── utils │ └── linked_list_node.dart ├── c++ ├── Chapter 1 │ ├── Question1_2 │ │ ├── Question1_2.h │ │ └── Question1_2.cpp │ ├── Question1_4 │ │ └── Question1_4.h │ ├── Question1_8 │ │ ├── Question1_8.h │ │ └── Question1_8.cpp │ ├── Question1_3 │ │ ├── Question1_3.h │ │ ├── Question1_3_B.h │ │ ├── Question1_3_B.cpp │ │ └── Question1_3.cpp │ ├── Question1_1 │ │ └── Question1_1.h │ ├── Question1_6 │ │ └── Question1_6.h │ ├── Question1_7 │ │ └── Question1_7.h │ ├── Question1_5 │ │ └── Question1_5.h │ └── main.cpp └── ctci.sln └── C └── Chapter_1 └── Question1_1 └── ChapQ1.1.c /objective c/README.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python/Chapter 2/classes/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/.DS_Store -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/CD.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class CD { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 5/Question5_7.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 5/Question5_7.zip -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/System.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class System { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_6/Line.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 7/Question7_6/Line.java -------------------------------------------------------------------------------- /java/Chapter 11/Question11_6/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 11/Question11_6/.DS_Store -------------------------------------------------------------------------------- /java/Chapter 11/Question11_7/HtWt.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 11/Question11_7/HtWt.java -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Square.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 7/Question7_5/Square.java -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Color.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public enum Color { 4 | White, Black 5 | } 6 | -------------------------------------------------------------------------------- /python/Chapter 2/classes/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/python/Chapter 2/classes/__init__.pyc -------------------------------------------------------------------------------- /java/Chapter 1/Question1_3/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 1/Question1_3/Question.java -------------------------------------------------------------------------------- /java/Chapter 2/Question2_1/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 2/Question2_1/Question.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_6/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 4/Question4_6/Question.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_7/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 4/Question4_7/Question.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_7/QuestionC.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 4/Question4_7/QuestionC.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_8/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 4/Question4_8/Question.java -------------------------------------------------------------------------------- /java/Chapter 5/Question5_1/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 5/Question5_1/Question.java -------------------------------------------------------------------------------- /java/Chapter 9/Question9_6/QuestionB.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 9/Question9_6/QuestionB.java -------------------------------------------------------------------------------- /java/Chapter 10/Question10_3/QuestionB.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 10/Question10_3/QuestionB.java -------------------------------------------------------------------------------- /java/Chapter 18/Question18_1/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 18/Question18_1/Question.java -------------------------------------------------------------------------------- /java/Chapter 18/Question18_3/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 18/Question18_3/Question.java -------------------------------------------------------------------------------- /java/Chapter 18/Question18_9/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 18/Question18_9/Question.java -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/CallHandler.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 8/Question8_2/CallHandler.java -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Direction.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public enum Direction { 4 | left, right, up, down 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_2/IntWrapper.java: -------------------------------------------------------------------------------- 1 | package Question2_2; 2 | 3 | public class IntWrapper { 4 | public int value = 0; 5 | } 6 | -------------------------------------------------------------------------------- /java/CtCILibrary/CtCILibrary/AssortedMethods.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/CtCILibrary/CtCILibrary/AssortedMethods.java -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ctci 2 | ==== 3 | 4 | Solutions for "Cracking the Coding Interview v5" 5 | 6 | Due to copyrights , the questions themselves are not published 7 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/RequestStatus.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public enum RequestStatus { 4 | Unread, Read, Accepted, Rejected 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/VehicleSize.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public enum VehicleSize { 4 | Motorcycle, 5 | Compact, 6 | Large, 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/UserStatusType.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public enum UserStatusType { 4 | Offline, Away, Idle, Available, Busy 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/Song.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class Song { 4 | private String songName; 5 | public String toString() { return songName; } 6 | } 7 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_13/bi_node.dart: -------------------------------------------------------------------------------- 1 | library binode; 2 | 3 | class BiNode { 4 | BiNode node1; 5 | BiNode node2; 6 | int data; 7 | BiNode(this.data); 8 | } 9 | 10 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Manager.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | class Manager extends Employee { 4 | public Manager() { 5 | rank = Rank.Manager; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_5/IntWrapper.java: -------------------------------------------------------------------------------- 1 | package Question4_5; 2 | 3 | public class IntWrapper { 4 | public IntWrapper(int m) { 5 | data = m; 6 | } 7 | public int data; 8 | } 9 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Square Cut Tester - Chapter 10, Problem 5.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faif/ctci/HEAD/java/Chapter 7/Question7_5/Square Cut Tester - Chapter 10, Problem 5.xlsx -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Director.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | class Director extends Employee { 4 | public Director() { 5 | rank = Rank.Director; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Respondent.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | class Respondent extends Employee { 4 | public Respondent() { 5 | rank = Rank.Responder; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_11/square_cell.dart: -------------------------------------------------------------------------------- 1 | library SquareCell; 2 | 3 | class SquareCell { 4 | int zerosRight = 0; 5 | int zerosBelow = 0; 6 | SquareCell(this.zerosRight, this.zerosBelow); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_5/PartialSum.java: -------------------------------------------------------------------------------- 1 | package Question2_5; 2 | 3 | import CtCILibrary.LinkedListNode; 4 | 5 | public class PartialSum { 6 | public LinkedListNode sum = null; 7 | public int carry = 0; 8 | } 9 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_11/subsquare.dart: -------------------------------------------------------------------------------- 1 | library Subsquare; 2 | 3 | class Subsquare { 4 | int row, column, size; 5 | Subsquare(this.row, this.column, this.size); 6 | String toString() => "($row, $column, $size)"; 7 | } 8 | 9 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Ambiguous.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Ambiguous extends Shape { 4 | private double area = 10; 5 | 6 | public double computeArea() { 7 | return area; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_6/Parts.java: -------------------------------------------------------------------------------- 1 | package Question18_6; 2 | 3 | public class Parts { 4 | public int left; 5 | public int right; 6 | public Parts(int l, int r) { 7 | left = l; 8 | right = r; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_2/Question1_2.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_2_h__ 2 | #define __Question_1_2_h__ 3 | 4 | class Question1_2 { 5 | public: 6 | int run(); 7 | void reverse(char* str); 8 | }; 9 | 10 | #endif // __Question_1_2_h__ -------------------------------------------------------------------------------- /java/Chapter 17/Question17_13/BiNode.java: -------------------------------------------------------------------------------- 1 | package Question17_13; 2 | 3 | public class BiNode { 4 | public BiNode node1; 5 | public BiNode node2; 6 | public int data; 7 | public BiNode(int d) { 8 | data = d; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_3/Node.java: -------------------------------------------------------------------------------- 1 | package Question3_3; 2 | 3 | public class Node { 4 | public Node above; 5 | public Node below; 6 | public int value; 7 | public Node(int value) { 8 | this.value = value; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Dog.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public class Dog extends Animal { 4 | public Dog(String n) { 5 | super(n); 6 | } 7 | 8 | public String name() { 9 | return "Dog: " + name; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Shape.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public abstract class Shape { 4 | public void printMe() { 5 | System.out.println("I am a shape."); 6 | } 7 | 8 | public abstract double computeArea(); 9 | } 10 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Caller.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | public class Caller { 4 | private String name; 5 | private int userId; 6 | public Caller(int id, String nm) { 7 | name = nm; 8 | userId = id; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_2/revstr.py: -------------------------------------------------------------------------------- 1 | def revStr(s): 2 | return s[::-1] 3 | 4 | if __name__ == '__main__': 5 | words = ('mary', 'anna', 'peter', 'hello world') 6 | for w in words: 7 | print('revStr({}): {}'.format(w, revStr(w))) 8 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Cat.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public class Cat extends Animal { 4 | public Cat(String n) { 5 | super(n); 6 | } 7 | 8 | public String name() { 9 | return "Cat: " + name; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_4/Question1_4.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_4_h__ 2 | #define __Question_1_4_h__ 3 | 4 | class Question1_4 { 5 | public: 6 | int run(); 7 | void replaceSpaces(char str[], int length); 8 | }; 9 | 10 | #endif // __Question_1_4_h__ -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Test.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | public class Test { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | CallHandler ch = CallHandler.getInstance(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/NodeWithMin.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | class NodeWithMin { 4 | public int value; 5 | public int min; 6 | public NodeWithMin(int v, int min){ 7 | value = v; 8 | this.min = min; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_2/Result.java: -------------------------------------------------------------------------------- 1 | package Question2_2; 2 | 3 | import CtCILibrary.*; 4 | 5 | public class Result { 6 | public LinkedListNode node; 7 | public int count; 8 | public Result(LinkedListNode n, int c) { 9 | node = n; 10 | count = c; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_4/replace.py: -------------------------------------------------------------------------------- 1 | def replaceSpaces(s): 2 | return '%20'.join(s.split()) 3 | 4 | if __name__ == '__main__': 5 | words = ( 'hello world ', ' mr. john ', '', ' ', ) 6 | for w in words: 7 | print('replaceSpaces({}): {}'.format(w, replaceSpaces(w))) 8 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_8/IntComparable.java: -------------------------------------------------------------------------------- 1 | package Question11_8; 2 | 3 | import java.util.Comparator; 4 | 5 | public class IntComparable implements Comparator{ 6 | 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | return o1.compareTo(o2); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /dart/Chapter5/Question5_6/question.dart: -------------------------------------------------------------------------------- 1 | int swapOddEvenBits(int x) { 2 | return (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); 3 | } 4 | 5 | void main() { 6 | int a = 103217; 7 | print ("$a: ${a.toRadixString(2)}"); 8 | int b = swapOddEvenBits(a); 9 | print("$b: ${b.toRadixString(2)}"); 10 | } -------------------------------------------------------------------------------- /java/Chapter 10/Question10_7/Node.java: -------------------------------------------------------------------------------- 1 | package Question10_7; 2 | 3 | public class Node { 4 | public Node prev; 5 | public Node next; 6 | public String[] results; 7 | public String query; 8 | 9 | public Node(String q, String[] res) { 10 | results = res; 11 | query = q; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Square.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Square extends Shape { 4 | private double len = 5; 5 | public void printMe() { 6 | System.out.println("I am a square."); 7 | } 8 | 9 | public double computeArea() { 10 | return len * len; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/GroupChat.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class GroupChat extends Conversation { 4 | public void removeParticipant(User user) { 5 | participants.remove(user); 6 | } 7 | 8 | public void addParticipant(User user) { 9 | participants.add(user); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Circle.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Circle extends Shape { 4 | private double rad = 5; 5 | public void printMe() { 6 | System.out.println("I am a circle."); 7 | } 8 | 9 | public double computeArea() { 10 | return rad * rad * 3.15; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Rank.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | public enum Rank { 4 | Responder (0), 5 | Manager (1), 6 | Director (2); 7 | 8 | private int value; 9 | 10 | private Rank(int v) { 11 | value = v; 12 | } 13 | 14 | public int getValue() { 15 | return value; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/SongSelector.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | 4 | public class SongSelector { 5 | private Song currentSong; 6 | public SongSelector(Song s) { currentSong=s; } 7 | public void setSong(Song s) { currentSong = s; } 8 | public Song getCurrentSong() { return currentSong; } 9 | } 10 | 11 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_6/GraphPoint.java: -------------------------------------------------------------------------------- 1 | package Question7_6; 2 | 3 | public class GraphPoint { 4 | public double x; 5 | public double y; 6 | public GraphPoint(double x1, double y1) { 7 | x = x1; 8 | y = y1; 9 | } 10 | 11 | public String toString() { 12 | return "(" + x + ", " + y + ")"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 14/Question14_5/Rectangle.java: -------------------------------------------------------------------------------- 1 | package Question14_5; 2 | 3 | public class Rectangle { 4 | private double width; 5 | private double height; 6 | public Rectangle(double w, double h) { 7 | width = w; 8 | height = h; 9 | } 10 | 11 | public double area() { 12 | return width * height; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_8/Question1_8.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_8_h__ 2 | #define __Question_1_8_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_8 { 9 | public: 10 | string result(bool value); 11 | bool isRotation(const string& s1, const string& s2); 12 | int run(); 13 | }; 14 | 15 | #endif // __Question_1_8_h__ -------------------------------------------------------------------------------- /java/Chapter 10/Question10_2/Machine.java: -------------------------------------------------------------------------------- 1 | package Question10_2; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Machine { 6 | public HashMap persons = new HashMap(); 7 | public int machineID; 8 | 9 | public Person getPersonWithID(int personID) { 10 | return persons.get(personID); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_3/Question1_3.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_3_h__ 2 | #define __Question_1_3_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_3 { 9 | public: 10 | int run(); 11 | bool permutation(const string& a, const string& b); 12 | string result(bool value); 13 | }; 14 | 15 | 16 | 17 | #endif // __Question_1_3_h__ -------------------------------------------------------------------------------- /java/Chapter 18/Question18_7/LengthComparator.java: -------------------------------------------------------------------------------- 1 | package Question18_7; 2 | 3 | import java.util.Comparator; 4 | 5 | public class LengthComparator implements Comparator { 6 | public int compare(String o1, String o2) { 7 | if (o1.length() < o2.length()) return 1; 8 | if (o1.length() > o2.length()) return -1; 9 | return 0; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_11/Subsquare.java: -------------------------------------------------------------------------------- 1 | package Question18_11; 2 | 3 | public class Subsquare { 4 | public int row, column, size; 5 | public Subsquare(int r, int c, int sz) { 6 | row = r; 7 | column = c; 8 | size = sz; 9 | } 10 | 11 | public void print() { 12 | System.out.println("(" + row + ", " + column + ", " + size + ")"); 13 | } 14 | } -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Line.java: -------------------------------------------------------------------------------- 1 | package Question7_5; 2 | 3 | public class Line { 4 | public Point start; 5 | public Point end; 6 | public Line(Point start, Point end) { 7 | this.start = start; 8 | this.end = end; 9 | } 10 | 11 | public String toString() { 12 | return "Line from " + start.toString() + " to " + end.toString(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_3/Question1_3_B.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_3_B_h__ 2 | #define __Question_1_3_B_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_3_B { 9 | public: 10 | int run(); 11 | bool permutation(const string& a, const string& b); 12 | string result(bool value); 13 | }; 14 | 15 | 16 | 17 | #endif // __Question_1_3_B_h__ -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronizedBlocks/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronizedBlocks; 2 | 3 | public class MyClass extends Thread { 4 | private String name; 5 | private MyObject myObj; 6 | 7 | public MyClass(MyObject obj, String n) { 8 | name = n; 9 | myObj = obj; 10 | } 11 | 12 | public void run() { 13 | myObj.foo(name); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_1/Question1_1.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_1_h__ 2 | #define __Question_1_1_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_1 { 9 | public: 10 | int run(); 11 | bool isUniqueChars(const string& str); 12 | bool isUniqueChars2(const string& str); 13 | string result(bool value); 14 | }; 15 | 16 | #endif // __Question_1_1_h__ -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Motorcycle.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class Motorcycle extends Vehicle { 4 | public Motorcycle() { 5 | spotsNeeded = 1; 6 | size = VehicleSize.Motorcycle; 7 | } 8 | 9 | public boolean canFitInSpot(ParkingSpot spot) { 10 | return true; 11 | } 12 | 13 | public void print() { 14 | System.out.print("M"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Bus.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class Bus extends Vehicle { 4 | public Bus() { 5 | spotsNeeded = 5; 6 | size = VehicleSize.Large; 7 | } 8 | 9 | public boolean canFitInSpot(ParkingSpot spot) { 10 | return spot.getSize() == VehicleSize.Large; 11 | } 12 | 13 | public void print() { 14 | System.out.print("B"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /python/Chapter 2/deletenode.py: -------------------------------------------------------------------------------- 1 | from classes.linkedlist import * 2 | 3 | def deleteNode(n): 4 | if not n or not n.next: 5 | return 6 | 7 | n.data = n.next.data 8 | n.next = n.next.next 9 | 10 | if __name__ == '__main__': 11 | ml = LinkedList(1) 12 | [ml.append(i) for i in range(2, 6)] 13 | print(ml) 14 | n = ml.kth(3) 15 | deleteNode(n) 16 | print(ml) 17 | -------------------------------------------------------------------------------- /dart/Chapter4/Question4_3/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/tree_node.dart'; 2 | 3 | void main() { 4 | List array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 5 | 6 | // We needed this code for other files, so check out the code in the library. 7 | TreeNode root = TreeNode.createMinimalBST(array); 8 | print("Root? ${root.data}"); 9 | print("Created BST? ${root.isBST()}"); 10 | print("Height: ${root.height()}"); 11 | } -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Point.java: -------------------------------------------------------------------------------- 1 | package Question7_5; 2 | 3 | public class Point { 4 | public double x; 5 | public double y; 6 | public Point(double x, double y) { 7 | this.x = x; 8 | this.y = y; 9 | } 10 | 11 | public boolean isEqual(Point p) { 12 | return (p.x == x && p.y == y); 13 | } 14 | 15 | public String toString() { 16 | return "(" + x + ", " + y + ")"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_9/MinHeapComparator.java: -------------------------------------------------------------------------------- 1 | package Question18_9; 2 | 3 | import java.util.Comparator; 4 | 5 | public class MinHeapComparator implements Comparator{ 6 | // Comparator that sorts integers from lowest to highest 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | if (o1 > o2) return 1; 10 | else if (o1 == o2) return 0; 11 | else return -1; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Piece.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Piece { 4 | private Color color; 5 | 6 | public Piece(Color c) { 7 | color = c; 8 | } 9 | 10 | public void flip() { 11 | if (color == Color.Black) { 12 | color = Color.White; 13 | } else { 14 | color = Color.Black; 15 | } 16 | } 17 | 18 | public Color getColor() { 19 | return color; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionB/ExampleB.java: -------------------------------------------------------------------------------- 1 | package IntroductionB; 2 | 3 | public class ExampleB { 4 | public static void main(String args[]) { 5 | ThreadExample instance = new ThreadExample(); 6 | instance.start(); 7 | 8 | while (instance.count != 5) { 9 | try { 10 | Thread.sleep(250); 11 | } catch (InterruptedException exc) { 12 | exc.printStackTrace(); 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_3; 2 | 3 | public class Question { 4 | public static void main(String[] args) { 5 | int capacity_per_substack = 5; 6 | SetOfStacks set = new SetOfStacks(capacity_per_substack); 7 | for (int i = 0; i < 34; i++) { 8 | set.push(i); 9 | } 10 | for (int i = 0; i < 34; i++) { 11 | System.out.println("Popped " + set.pop()); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Car.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class Car extends Vehicle { 4 | public Car() { 5 | spotsNeeded = 1; 6 | size = VehicleSize.Compact; 7 | } 8 | 9 | public boolean canFitInSpot(ParkingSpot spot) { 10 | return spot.getSize() == VehicleSize.Large || spot.getSize() == VehicleSize.Compact; 11 | } 12 | 13 | public void print() { 14 | System.out.print("C"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | ctci java 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/Message.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | import java.util.Date; 4 | 5 | public class Message { 6 | private String content; 7 | private Date date; 8 | public Message(String content, Date date) { 9 | this.content = content; 10 | this.date = date; 11 | } 12 | 13 | public String getContent() { 14 | return content; 15 | } 16 | 17 | public Date getDate() { 18 | return date; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_6/Question1_6.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_6_h__ 2 | #define __Question_1_6_h__ 3 | 4 | class Question1_6 { 5 | public: 6 | /** 7 | * Since we can't provide variable matrix size in C++, we will do it "the c way" and will provide a 1-dimensional 8 | * array 9 | */ 10 | void rotate(int* matrix, int n); 11 | void printMatrix(int* matrix, int m, int n); 12 | int run(); 13 | }; 14 | 15 | #endif // __Question_1_6_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_7/Question1_7.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_7_h__ 2 | #define __Question_1_7_h__ 3 | 4 | class Question1_7 { 5 | public: 6 | /** 7 | * Since we can't provide variable matrix size in C++, we will do it "the c way" and will provide a 1-dimensional 8 | * array 9 | */ 10 | void setZeros(int* matrix, int m, int n); 11 | void printMatrix(int* matrix, int m, int n); 12 | int run(); 13 | }; 14 | 15 | #endif // __Question_1_7_h__ -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionWaitNotify/MyObject.java: -------------------------------------------------------------------------------- 1 | package IntroductionWaitNotify; 2 | 3 | public class MyObject { 4 | public void foo(String name) { 5 | try { 6 | System.out.println("Thread " + name + ".foo(): starting"); 7 | Thread.sleep(3000); 8 | System.out.println("Thread " + name + ".foo(): ending"); 9 | } catch (InterruptedException exc) { 10 | System.out.println("Thread " + name + ": interrupted."); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_9/MaxHeapComparator.java: -------------------------------------------------------------------------------- 1 | package Question18_9; 2 | 3 | import java.util.Comparator; 4 | 5 | public class MaxHeapComparator implements Comparator{ 6 | // Comparator that sorts integers from highest to lowest 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | // TODO Auto-generated method stub 10 | if (o1 < o2) return 1; 11 | else if (o1 == o2) return 0; 12 | else return -1; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/Playlist.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | import java.util.Queue; 4 | 5 | public class Playlist { 6 | private Song song; 7 | private Queue queue; 8 | public Playlist(Song song, Queue queue) { 9 | super(); 10 | this.song = song; 11 | this.queue = queue; 12 | } 13 | 14 | public Song getNextSongToPlay(){ return queue.peek(); } 15 | public void queueUpSong(Song s){ queue.add(s); } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_3/Chopstick.java: -------------------------------------------------------------------------------- 1 | package Question16_3; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Chopstick { 7 | private Lock lock; 8 | 9 | public Chopstick() { 10 | lock = new ReentrantLock(); 11 | } 12 | 13 | public boolean pickUp() { 14 | return lock.tryLock(); 15 | } 16 | 17 | public void putDown() { 18 | lock.unlock(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_6/MyThread.java: -------------------------------------------------------------------------------- 1 | package Question16_6; 2 | 3 | public class MyThread extends Thread { 4 | private Foo foo; 5 | public String name; 6 | public String firstMethod; 7 | public MyThread(Foo f, String nm, String fM) { 8 | foo = f; 9 | name = nm; 10 | firstMethod = fM; 11 | } 12 | 13 | public void run() { 14 | if (firstMethod.equals("A")) { 15 | foo.methodA(name); 16 | } else { 17 | foo.methodB(name); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_11/SquareCell.java: -------------------------------------------------------------------------------- 1 | package Question18_11; 2 | 3 | public class SquareCell { 4 | public int zerosRight = 0; 5 | public int zerosBelow = 0; 6 | public SquareCell(int right, int below) { 7 | zerosRight = right; 8 | zerosBelow = below; 9 | } 10 | 11 | public void setZerosRight(int right) { 12 | zerosRight = right; 13 | } 14 | 15 | public void setZerosBelow(int below) { 16 | zerosBelow = below; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/hand.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | class Hand { 4 | 5 | List cards = new List(); 6 | 7 | int score() { 8 | int score = 0; 9 | for (T card in cards) { 10 | score += card.value(); 11 | } 12 | return score; 13 | } 14 | 15 | void addCard(T card) { 16 | cards.add(card); 17 | } 18 | 19 | void print_cards() { 20 | for (Card card in cards) { 21 | card.print_card(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/UserStatus.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class UserStatus { 4 | private String message; 5 | private UserStatusType type; 6 | public UserStatus(UserStatusType type, String message) { 7 | this.type = type; 8 | this.message = message; 9 | } 10 | 11 | public UserStatusType getStatusType() { 12 | return type; 13 | } 14 | 15 | public String getMessage() { 16 | return message; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Location.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Location { 4 | private int row; 5 | private int column; 6 | public Location(int r, int c) { 7 | row = r; 8 | column = c; 9 | } 10 | 11 | public boolean isSameAs(int r, int c) { 12 | return row == r && column == c; 13 | } 14 | 15 | public int getRow() { 16 | return row; 17 | } 18 | 19 | public int getColumn() { 20 | return column; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_10/Dummy.java: -------------------------------------------------------------------------------- 1 | package Question8_10; 2 | 3 | public class Dummy { 4 | private String name; 5 | private int age; 6 | public Dummy(String n, int a) { 7 | name = n; 8 | age = a; 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return "(" + name + ", " + age + ")"; 14 | } 15 | 16 | public int getAge() { 17 | return age; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_8/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int getMaxSum(List a) { 3 | int maxSum = 0; 4 | int runningSum = 0; 5 | for (int i = 0; i < a.length; i++) { 6 | runningSum += a[i]; 7 | if (maxSum < runningSum) { 8 | maxSum = runningSum; 9 | } else if (runningSum < 0) { 10 | runningSum = 0; 11 | } 12 | } 13 | 14 | return maxSum; 15 | } 16 | 17 | void main() { 18 | List a = [2, -8, 3, -2, 4, -10]; 19 | print(getMaxSum(a)); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronization/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronization; 2 | 3 | public class MyClass extends Thread { 4 | private String name; 5 | private MyObject myObj; 6 | 7 | public MyClass(MyObject obj, String n) { 8 | name = n; 9 | myObj = obj; 10 | } 11 | 12 | public void run() { 13 | if (name.equals("1")) { 14 | MyObject.foo(name); 15 | } else if (name.equals("2")) { 16 | MyObject.bar(name); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_9/File.java: -------------------------------------------------------------------------------- 1 | package Question8_9; 2 | 3 | public class File extends Entry { 4 | private String content; 5 | private int size; 6 | 7 | public File(String n, Directory p, int sz) { 8 | super(n, p); 9 | size = sz; 10 | } 11 | 12 | public int size() { 13 | return size; 14 | } 15 | 16 | public String getContents() { 17 | return content; 18 | } 19 | 20 | public void setContents(String c) { 21 | content = c; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_8/SuffixTree.java: -------------------------------------------------------------------------------- 1 | package Question18_8; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class SuffixTree { 6 | SuffixTreeNode root = new SuffixTreeNode(); 7 | 8 | public SuffixTree(String s) { 9 | for (int i = 0; i < s.length(); i++) { 10 | String suffix = s.substring(i); 11 | root.insertString(suffix, i); 12 | } 13 | } 14 | 15 | public ArrayList search(String s) { 16 | return root.search(s); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /dart/README.md: -------------------------------------------------------------------------------- 1 | INTRODUCTION 2 | ------------ 3 | 4 | Cracking the Coding Interview with Dart. The collection of dart code contains 5 | the solutions to ctci. This was a quick port of some of the solutions found in 6 | the java solution manual. Going forward these solutions will be dartified. Buy 7 | the book and support the author. [Cracking the Coding Interview](http://www.amazon.com/dp/098478280X/) 8 | 9 | TODO 10 | ---- 11 | 12 | Chapter 8 is not finished. 13 | Chapter 10 is not finished. 14 | 15 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_2/AnagramComparator.java: -------------------------------------------------------------------------------- 1 | package Question11_2; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | public class AnagramComparator implements Comparator { 7 | public String sortChars(String s) { 8 | char[] content = s.toCharArray(); 9 | Arrays.sort(content); 10 | return new String(content); 11 | } 12 | 13 | public int compare(String s1, String s2) { 14 | return sortChars(s1).compareTo(sortChars(s2)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/StackWithMin.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackWithMin extends Stack { 6 | public void push(int value) { 7 | int newMin = Math.min(value, min()); 8 | super.push(new NodeWithMin(value, newMin)); 9 | } 10 | 11 | public int min() { 12 | if (this.isEmpty()) { 13 | return Integer.MAX_VALUE; 14 | } else { 15 | return peek().min; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Animal.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public abstract class Animal { 4 | private int order; 5 | protected String name; 6 | public Animal(String n) { 7 | name = n; 8 | } 9 | 10 | public abstract String name(); 11 | 12 | public void setOrder(int ord) { 13 | order = ord; 14 | } 15 | 16 | public int getOrder() { 17 | return order; 18 | } 19 | 20 | public boolean isOlderThan(Animal a) { 21 | return this.order < a.getOrder(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionWaitNotify/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionWaitNotify; 2 | 3 | public class MyClass extends Thread { 4 | private String name; 5 | private MyObject myObj; 6 | 7 | public MyClass(MyObject obj, String n) { 8 | name = n; 9 | myObj = obj; 10 | } 11 | 12 | public void run() { 13 | try { 14 | myObj.wait(1000); 15 | myObj.foo(name); 16 | myObj.notify(); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Player.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Player { 4 | private Color color; 5 | public Player(Color c) { 6 | color = c; 7 | } 8 | 9 | public int getScore() { 10 | return Game.getInstance().getBoard().getScoreForColor(color); 11 | } 12 | 13 | public boolean playPiece(int row, int column) { 14 | return Game.getInstance().getBoard().placeColor(row, column, color); 15 | } 16 | 17 | public Color getColor() { 18 | return color; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_5/MyThread.java: -------------------------------------------------------------------------------- 1 | package Question16_5; 2 | 3 | public class MyThread extends Thread { 4 | private String method; 5 | private Foo foo; 6 | 7 | public MyThread(Foo foo, String method) { 8 | this.method = method; 9 | this.foo = foo; 10 | } 11 | 12 | public void run() { 13 | if (method == "first") { 14 | foo.first(); 15 | } else if (method == "second") { 16 | foo.second(); 17 | } else if (method == "third") { 18 | foo.third(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/PrivateChat.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class PrivateChat extends Conversation { 4 | public PrivateChat(User user1, User user2) { 5 | participants.add(user1); 6 | participants.add(user2); 7 | } 8 | 9 | public User getOtherParticipant(User primary) { 10 | if (participants.get(0) == primary) { 11 | return participants.get(1); 12 | } else if (participants.get(1) == primary) { 13 | return participants.get(0); 14 | } 15 | return null; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.awt.Point; 6 | 7 | public class Question { 8 | 9 | public static void main(String[] args) { 10 | Game game = Game.getInstance(); 11 | game.getBoard().initialize(); 12 | game.getBoard().printBoard(); 13 | Automator automator = Automator.getInstance(); 14 | while (!automator.isOver() && automator.playRandom()) { 15 | } 16 | automator.printScores(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronizedBlocks/MyObject.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronizedBlocks; 2 | 3 | public class MyObject { 4 | public void foo(String name) { 5 | synchronized(this) { 6 | try { 7 | System.out.println("Thread " + name + ".foo(): starting"); 8 | Thread.sleep(3000); 9 | System.out.println("Thread " + name + ".foo(): ending"); 10 | } catch (InterruptedException exc) { 11 | System.out.println("Thread " + name + ": interrupted."); 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_2/Graph.java: -------------------------------------------------------------------------------- 1 | package Question4_2; 2 | 3 | public class Graph { 4 | private Node vertices[]; 5 | public int count; 6 | public Graph() { 7 | vertices = new Node[6]; 8 | count = 0; 9 | } 10 | 11 | public void addNode(Node x) { 12 | if (count < 30) { 13 | vertices[count] = x; 14 | count++; 15 | } else { 16 | System.out.print("Graph full"); 17 | } 18 | } 19 | 20 | public Node[] getNodes() { 21 | return vertices; 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_5/Question1_5.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_5_h__ 2 | #define __Question_1_5_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_5 { 9 | public: 10 | int run(); 11 | int stringToInt(const string& value); 12 | string intToString(int value); 13 | int countCompression(const string& str); 14 | 15 | /// C++ std::string is efficient and no need to use a "StringBuffer"-like structure. 16 | string compressBetter(const string& str); 17 | }; 18 | 19 | 20 | 21 | #endif // __Question_1_5_h__ -------------------------------------------------------------------------------- /dart/Chapter18/Question18_2/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | void shuffleArray(List cards) { 6 | int temp; 7 | int index; 8 | for (int i = 0; i < cards.length; i++) { 9 | index = (random.nextDouble() * (cards.length - i)).toInt() + i; 10 | temp = cards[i]; 11 | cards[i] = cards[index]; 12 | cards[index] = temp; 13 | } 14 | } 15 | 16 | void main() { 17 | List cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; 18 | print(cards); 19 | shuffleArray(cards); 20 | print(cards); 21 | } -------------------------------------------------------------------------------- /java/Chapter 11/Question11_2/Question.java: -------------------------------------------------------------------------------- 1 | package Question11_2; 2 | 3 | import java.util.Arrays; 4 | 5 | import CtCILibrary.AssortedMethods; 6 | 7 | public class Question { 8 | public static void main(String[] args) { 9 | String[] array = {"apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee"}; 10 | System.out.println(AssortedMethods.stringArrayToString(array)); 11 | Arrays.sort(array, new AnagramComparator()); 12 | System.out.println(AssortedMethods.stringArrayToString(array)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_1/Hand.java: -------------------------------------------------------------------------------- 1 | package Question8_1; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Hand { 6 | protected ArrayList cards = new ArrayList(); 7 | 8 | public int score() { 9 | int score = 0; 10 | for (T card : cards) { 11 | score += card.value(); 12 | } 13 | return score; 14 | } 15 | 16 | public void addCard(T card) { 17 | cards.add(card); 18 | } 19 | 20 | public void print() { 21 | for (Card card : cards) { 22 | card.print(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_3/anagram.py: -------------------------------------------------------------------------------- 1 | def anagram(s1, s2): 2 | s1 = s1.lower() 3 | s2 = s2.lower() 4 | # sort, convert to str and strip 5 | s1 = ''.join(sorted(s1)).strip() 6 | s2 = ''.join(sorted(s2)).strip() 7 | return s1 == s2 8 | 9 | 10 | if __name__ == '__main__': 11 | words = ( ('So dark the con of man', 'Madonna of The Rocks'), 12 | (' ba ', ' Ab '), 13 | ('anne', 'annea') ) 14 | for w1, w2 in words: 15 | print('anagram({}, {}): {}'.format(w1, w2, anagram(w1, w2))) 16 | -------------------------------------------------------------------------------- /dart/Chapter11/Question11_2/question.dart: -------------------------------------------------------------------------------- 1 | class AnagramComparator { 2 | static String sortChars(String s) { 3 | List content = s.split(''); 4 | content.sort(); 5 | return content.join(''); 6 | } 7 | 8 | static int compare(String s1, String s2) { 9 | return sortChars(s1).compareTo(sortChars(s2)); 10 | } 11 | } 12 | 13 | void main() { 14 | List array = ["apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee"]; 15 | print(array); 16 | array.sort(AnagramComparator.compare); 17 | print(array); 18 | } -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionB/ThreadExample.java: -------------------------------------------------------------------------------- 1 | package IntroductionB; 2 | 3 | public class ThreadExample extends Thread { 4 | int count = 0; 5 | 6 | public void run() { 7 | System.out.println("Thread starting."); 8 | try { 9 | while (count < 5) { 10 | Thread.sleep(500); 11 | System.out.println("In Thread, count is " + count); 12 | count++; 13 | } 14 | } catch (InterruptedException exc) { 15 | System.out.println("Thread interrupted."); 16 | } 17 | System.out.println("Thread terminating."); 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question4_3; 2 | 3 | import CtCILibrary.TreeNode; 4 | 5 | public class Question { 6 | public static void main(String[] args) { 7 | int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 8 | 9 | // We needed this code for other files, so check out the code in the library 10 | TreeNode root = TreeNode.createMinimalBST(array); 11 | System.out.println("Root? " + root.data); 12 | System.out.println("Created BST? " + root.isBST()); 13 | System.out.println("Height: " + root.height()); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 5/Question5_6/Question.java: -------------------------------------------------------------------------------- 1 | package Question5_6; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | 7 | public static int swapOddEvenBits(int x) { 8 | return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) ); 9 | } 10 | 11 | public static void main(String[] args) { 12 | int a = 103217; 13 | System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a)); 14 | int b = swapOddEvenBits(a); 15 | System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b)); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question18_8; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Question { 6 | public static void main(String[] args) { 7 | String testString = "mississippi"; 8 | String[] stringList = {"is", "sip", "hi", "sis"}; 9 | SuffixTree tree = new SuffixTree(testString); 10 | for (String s : stringList) { 11 | ArrayList list = tree.search(s); 12 | if (list != null) { 13 | System.out.println(s + ": " + list.toString()); 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/User.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class User { 4 | private String name; 5 | public String getName() { return name; } 6 | public void setName(String name) { this.name = name; } 7 | public long getID() { return ID; } 8 | public void setID(long iD) { ID = iD; } 9 | private long ID; 10 | public User(String name, long iD) { 11 | this.name = name; 12 | ID = iD; 13 | } 14 | public User getUser() { return this; } 15 | public static User addUser(String name, long iD){ 16 | return new User(name, iD); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_3/Line.java: -------------------------------------------------------------------------------- 1 | package Question7_3; 2 | 3 | 4 | public class Line { 5 | static double epsilon = 0.000001; 6 | public double slope; 7 | public double yintercept; 8 | 9 | public Line(double s, double y) { 10 | slope = s; 11 | yintercept = y; 12 | } 13 | 14 | public void print() { 15 | System.out.print("y = " + slope + "x + " + yintercept); 16 | } 17 | 18 | public boolean intersect(Line line2) { 19 | return Math.abs(slope - line2.slope) > epsilon || 20 | Math.abs(yintercept - line2.yintercept) < epsilon; 21 | } 22 | }; -------------------------------------------------------------------------------- /dart/Chapter17/Question17_1/question.dart: -------------------------------------------------------------------------------- 1 | 2 | void swap(int a, int b) { 3 | // Example for a = 9, b = 4 4 | a = a - b; // a = 9 - 4 = 5 5 | b = a + b; // b = 5 + 4 = 9 6 | a = b - a; // a = 9 - 5 7 | 8 | print("a: $a"); 9 | print("b: $b"); 10 | } 11 | 12 | void swap_opt(int a, int b) { 13 | a = a^b; 14 | b = a^b; 15 | a = a^b; 16 | 17 | print("a: $a"); 18 | print("b: $b"); 19 | } 20 | 21 | void main() { 22 | int a = 1672; 23 | int b = 9332; 24 | 25 | print("a: $a"); 26 | print("b: $b"); 27 | 28 | //swap(a, b); 29 | swap_opt(a, b); 30 | } 31 | 32 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/Conversation.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | import java.util.ArrayList; 4 | 5 | public abstract class Conversation { 6 | protected ArrayList participants = new ArrayList(); 7 | protected int id; 8 | protected ArrayList messages = new ArrayList(); 9 | 10 | public ArrayList getMessages() { 11 | return messages; 12 | } 13 | 14 | public boolean addMessage(Message m) { 15 | messages.add(m); 16 | return true; 17 | } 18 | 19 | public int getId() { 20 | return id; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_4/Q1_4.py: -------------------------------------------------------------------------------- 1 | """write a method to replace all space in a string with '%20' 2 | """ 3 | 4 | # using a list to store each char and change space to '%20', then join list into a string 5 | def replaceSpace(string): 6 | charList = [] 7 | for char in string: 8 | if char == ' ': 9 | char = '%20' 10 | charList.append(char) 11 | return ''.join(charList) 12 | 13 | #test 14 | inputStr = " Smith q m " 15 | expectOutput = "%20Smith%20%20%20%20q%20m%20" 16 | if replaceSpace(inputStr) == expectOutput: 17 | print "test passed" 18 | else: 19 | print "test failed" 20 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_5/compress.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | def compress(s): 4 | d = OrderedDict() 5 | for i in s: 6 | if i in d: 7 | d[i] += 1 8 | else: 9 | d[i] = 1 10 | cs = '' 11 | for i in zip(d.keys(), d.values()): 12 | cs += str(i[0]) # letter, eg. a 13 | cs += str(i[1]) # count, eg. 3 14 | return cs if len(cs) < len(s) else s 15 | 16 | if __name__ == '__main__': 17 | words = ('aaabbbbcccccdee', 'abc', 'a', '', ' ', 'aabccdde', 'aab', 'aaabb') 18 | for w in words: 19 | print('compress({}): {}'.format(w, compress(w))) 20 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_5/Question.java: -------------------------------------------------------------------------------- 1 | package Question16_5; 2 | 3 | public class Question { 4 | public static void main(String[] args) { 5 | Foo foo = new Foo(); 6 | 7 | MyThread thread1 = new MyThread(foo, "first"); 8 | MyThread thread2 = new MyThread(foo, "second"); 9 | MyThread thread3 = new MyThread(foo, "third"); 10 | 11 | thread3.start(); 12 | thread2.start(); 13 | thread1.start(); 14 | 15 | try { 16 | foo.sem3.acquire(); 17 | } catch (Exception e) { 18 | e.printStackTrace(); 19 | } 20 | foo.sem3.release(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/CDPlayer.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class CDPlayer { 4 | private Playlist p; 5 | private CD c; 6 | 7 | public Playlist getPlaylist() { return p; } 8 | public void setPlaylist(Playlist p) { this.p = p; } 9 | public CD getCD() { return c; } 10 | public void setCD(CD c) { this.c = c; } 11 | 12 | public CDPlayer(Playlist p) { this.p = p; } 13 | public CDPlayer(CD c, Playlist p) { 14 | this.p = p; 15 | this.c = c; 16 | } 17 | 18 | public CDPlayer(CD c){ this.c = c; } 19 | public void playSong(Song s) { } 20 | } 21 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_4/questionBrute.dart: -------------------------------------------------------------------------------- 1 | 2 | int numberOf2s(int n) { 3 | int count = 0; 4 | while (n > 0) { 5 | if (n % 10 == 2) { 6 | count++; 7 | } 8 | 9 | n = n ~/ 10; 10 | } 11 | 12 | return count; 13 | } 14 | 15 | int numberOf2sInRange(int n) { 16 | int count = 0; 17 | for (int i = 2; i <= n; i++) { // Might as well start at 2; 18 | count += numberOf2s(i); 19 | } 20 | 21 | return count; 22 | } 23 | 24 | void main() { 25 | for (int i = 0; i < 1000; i++) { 26 | int v = numberOf2sInRange(i); 27 | print("Between 0 and $i: $v"); 28 | } 29 | } -------------------------------------------------------------------------------- /dart/Chapter7/Introduction/prime_numbers.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | bool primeNaive(int n) { 4 | for (int i = 2; i < n; i++) { 5 | if (n % i == 0) { 6 | return false; 7 | } 8 | } 9 | return true; 10 | } 11 | 12 | bool primeSlightlyBetter(int n) { 13 | int s = sqrt(n).toInt(); 14 | for (int i = 2; i <= s; i++) { 15 | if (n % i == 0) { 16 | return false; 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | 23 | void main() { 24 | for (int i = 2; i < 100; i++) { 25 | if (primeSlightlyBetter(i)) { 26 | print(i); 27 | } 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /dart/Chapter3/Question3_6/question.dart: -------------------------------------------------------------------------------- 1 | 2 | List sort(List s) { 3 | List r = new List(); 4 | while (!s.isEmpty) { 5 | int tmp = s.removeLast(); 6 | while (!r.isEmpty && r.last > tmp) { 7 | s.add(r.removeLast()); 8 | } 9 | r.add(tmp); 10 | } 11 | 12 | return r; 13 | } 14 | 15 | void main() { 16 | 17 | List s = new List(); 18 | s.add(3); 19 | s.add(2); 20 | s.add(24); 21 | s.add(34); 22 | s.add(19); 23 | s.add(3); 24 | s.add(4); 25 | s = sort(s); 26 | while(!s.isEmpty) { 27 | print(s.removeLast()); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /java/Chapter 3/Question3_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_4; 2 | 3 | public class Question { 4 | public static void main(String[] args) { 5 | // Set up code. 6 | int n = 5; 7 | Tower[] towers = new Tower[3]; 8 | for (int i = 0; i < 3; i++) { 9 | towers[i] = new Tower(i); 10 | } 11 | for (int i = n - 1; i >= 0; i--) { 12 | towers[0].add(i); 13 | } 14 | 15 | // Copy and paste output into a .XML file and open it with internet explorer. 16 | //towers[0].print(); 17 | towers[0].moveDisks(n, towers[2], towers[1]); 18 | //towers[2].print(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/Book.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | public class Book { 4 | private int bookId; 5 | private String details; 6 | 7 | public Book(int id, String det) { 8 | bookId = id; 9 | details = det; 10 | } 11 | 12 | public void update() { } 13 | 14 | public int getID() { 15 | return bookId; 16 | } 17 | 18 | public void setID(int id) { 19 | bookId = id; 20 | } 21 | 22 | public String getDetails() { 23 | return details; 24 | } 25 | 26 | public void setDetails(String details) { 27 | this.details = details; 28 | } 29 | } -------------------------------------------------------------------------------- /java/Chapter 10/Question10_4/BitSet.java: -------------------------------------------------------------------------------- 1 | package Question10_4; 2 | 3 | class BitSet { 4 | int[] bitset; 5 | 6 | public BitSet(int size) { 7 | bitset = new int[size >> 5]; // divide by 32 8 | } 9 | 10 | boolean get(int pos) { 11 | int wordNumber = (pos >> 5); // divide by 32 12 | int bitNumber = (pos & 0x1F); // mod 32 13 | return (bitset[wordNumber] & (1 << bitNumber)) != 0; 14 | } 15 | 16 | void set(int pos) { 17 | int wordNumber = (pos >> 5); // divide by 32 18 | int bitNumber = (pos & 0x1F); // mod 32 19 | bitset[wordNumber] |= 1 << bitNumber; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_14/Result.java: -------------------------------------------------------------------------------- 1 | package Question17_14; 2 | 3 | public class Result { 4 | public int invalid = Integer.MAX_VALUE; 5 | public String parsed = ""; 6 | public Result(int inv, String p) { 7 | invalid = inv; 8 | parsed = p; 9 | } 10 | 11 | public Result clone() { 12 | return new Result(this.invalid, this.parsed); 13 | } 14 | 15 | public static Result min(Result r1, Result r2) { 16 | if (r1 == null) { 17 | return r2; 18 | } else if (r2 == null) { 19 | return r1; 20 | } 21 | 22 | return r2.invalid < r1.invalid ? r2 : r1; 23 | } 24 | } -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionA/RunnableThreadExample.java: -------------------------------------------------------------------------------- 1 | package IntroductionA; 2 | 3 | public class RunnableThreadExample implements Runnable { 4 | public int count = 0; 5 | 6 | public void run() { 7 | System.out.println("RunnableThread starting."); 8 | try { 9 | while (count < 5) { 10 | Thread.sleep(500); 11 | System.out.println("RunnableThread count: " + count); 12 | count++; 13 | } 14 | } catch (InterruptedException exc) { 15 | System.out.println("RunnableThread interrupted."); 16 | } 17 | System.out.println("RunnableThread terminating."); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_8; 2 | 3 | public class Question { 4 | 5 | public static int getMaxSum(int[] a) { 6 | int maxSum = 0; 7 | int runningSum = 0; 8 | for (int i = 0; i < a.length; i++) { 9 | runningSum += a[i]; 10 | if (maxSum < runningSum) { 11 | maxSum = runningSum; 12 | } else if (runningSum < 0) { 13 | runningSum = 0; 14 | } 15 | } 16 | return maxSum; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[] a = {2, -8, 3, -2, 4, -10}; 21 | System.out.println(getMaxSum(a)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionA/ExampleA.java: -------------------------------------------------------------------------------- 1 | package IntroductionA; 2 | 3 | public class ExampleA { 4 | 5 | public static void main(String[] args) { 6 | RunnableThreadExample instance = new RunnableThreadExample(); 7 | Thread thread = new Thread(instance); 8 | thread.start(); 9 | 10 | /* waits until earlier thread counts to 5 (slowly) */ 11 | while (instance.count != 5) { 12 | try { 13 | Thread.sleep(250); 14 | } catch (InterruptedException exc) { 15 | exc.printStackTrace(); 16 | } 17 | } 18 | 19 | System.out.println("Program Terminating."); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_10/Attribute.java: -------------------------------------------------------------------------------- 1 | package Question17_10; 2 | 3 | public class Attribute { 4 | public String tag; 5 | public String value; 6 | public Attribute(String t, String v) { 7 | tag = t; 8 | value = v; 9 | } 10 | 11 | public String getTagCode() { 12 | if (tag == "family") { 13 | return "1"; 14 | } else if (tag == "person") { 15 | return "2"; 16 | } else if (tag == "firstName") { 17 | return "3"; 18 | } else if (tag == "lastName") { 19 | return "4"; 20 | } else if (tag == "state") { 21 | return "5"; 22 | } 23 | return "--"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_1/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | int add(int a, int b) { 6 | if (b == 0) return a; 7 | 8 | int sum = a ^ b; // Add without carrying 9 | int carry = (a & b) << 1; // carry, but don't add 10 | return add(sum, carry); 11 | } 12 | 13 | int randomInt(int n) { 14 | return (random.nextDouble() * n).toInt(); 15 | } 16 | 17 | void main() { 18 | for (int i = 0; i < 100; i++) { 19 | int a = randomInt(10); 20 | int b = randomInt(10); 21 | int sum = add(a, b); 22 | print("$a + $b = $sum"); 23 | assert(sum == a + b); 24 | } 25 | } -------------------------------------------------------------------------------- /dart/Chapter17/Question17_12/question.dart: -------------------------------------------------------------------------------- 1 | 2 | void printPairSums(List array, int sum) { 3 | array.sort(); 4 | 5 | int first = 0; 6 | int last = array.length - 1; 7 | while (first < last) { 8 | int s = array[first] + array[last]; 9 | if (s == sum) { 10 | print("${array[first]} ${array[last]}"); 11 | ++first; 12 | --last; 13 | } else { 14 | if (s < sum) { 15 | ++first; 16 | } else { 17 | --last; 18 | } 19 | } 20 | } 21 | } 22 | 23 | void main() { 24 | List test = [9, 3, 6, 5, 7, -1, 13, 14, -2, 12, 0]; 25 | printPairSums(test, 12); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /python/Chapter 2/Question2_3.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | def deleteNode(linkedlist, node): 4 | if node.next != None: 5 | node.value = node.next.value 6 | node.next = node.next.next 7 | 8 | # if the given node is the last one, no way to delete it. 9 | # Here we set the last one's value to None 10 | else: 11 | node.value = None 12 | 13 | 14 | 15 | #-----------test-------------- 16 | L = randomLinkedList(5, 0, 100) 17 | node = L.head.next.next # Given access to the 3rd node 18 | print L 19 | print "After deleting the node" 20 | deleteNode(L, node) 21 | print L -------------------------------------------------------------------------------- /python/Chapter 4/Question4_7/BinaryTreeNode.py: -------------------------------------------------------------------------------- 1 | class BinaryTreeNode: 2 | 3 | def __init__(self, value): 4 | self.value = value 5 | self.left = None 6 | self.right = None 7 | self.parent = None 8 | 9 | def setLeft(self, leftvalue): 10 | leftnode = BinaryTreeNode(leftvalue) 11 | self.left = leftnode 12 | if leftnode != None: 13 | leftnode.parent = self 14 | 15 | def setRight(self, rightvalue): 16 | rightnode = BinaryTreeNode(rightvalue) 17 | self.right = rightnode 18 | if rightnode != None: 19 | rightnode.parent = self 20 | -------------------------------------------------------------------------------- /python/Chapter 4/Question4_9/BinaryTreeNode.py: -------------------------------------------------------------------------------- 1 | class BinaryTreeNode: 2 | 3 | def __init__(self, value): 4 | self.value = value 5 | self.left = None 6 | self.right = None 7 | self.parent = None 8 | 9 | def setLeft(self, leftvalue): 10 | leftnode = BinaryTreeNode(leftvalue) 11 | self.left = leftnode 12 | if leftnode != None: 13 | leftnode.parent = self 14 | 15 | def setRight(self, rightvalue): 16 | rightnode = BinaryTreeNode(rightvalue) 17 | self.right = rightnode 18 | if rightnode != None: 19 | rightnode.parent = self 20 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionWaitNotify/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionWaitNotify; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | MyObject obj1 = new MyObject(); 8 | MyObject obj2 = new MyObject(); 9 | MyClass thread1 = new MyClass(obj1, "1"); 10 | MyClass thread2 = new MyClass(obj1, "2"); 11 | 12 | thread1.start(); 13 | thread2.start(); 14 | 15 | Thread.sleep(3000 * 3); 16 | } catch (InterruptedException exc) { 17 | System.out.println("Program Interrupted."); 18 | } 19 | System.out.println("Program terminating."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_1/Suit.java: -------------------------------------------------------------------------------- 1 | package Question8_1; 2 | 3 | public enum Suit { 4 | Club (0), 5 | Diamond (1), 6 | Heart (2), 7 | Spade (3); 8 | 9 | private int value; 10 | private Suit(int v) { 11 | value = v; 12 | } 13 | 14 | public int getValue() { 15 | return value; 16 | } 17 | 18 | public static Suit getSuitFromValue(int value) { 19 | switch (value) { 20 | case 0: 21 | return Suit.Club; 22 | case 1: 23 | return Suit.Diamond; 24 | case 2: 25 | return Suit.Heart; 26 | case 3: 27 | return Suit.Spade; 28 | default: 29 | return null; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/JukeBox.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | import java.util.Set; 4 | 5 | public class JukeBox { 6 | private CDPlayer cdPlayer; 7 | private User user; 8 | private Set cdCollection; 9 | private SongSelector ts; 10 | 11 | public JukeBox(CDPlayer cdPlayer, User user, Set cdCollection, 12 | SongSelector ts) { 13 | super(); 14 | this.cdPlayer = cdPlayer; 15 | this.user = user; 16 | this.cdCollection = cdCollection; 17 | this.ts = ts; 18 | } 19 | 20 | public Song getCurrentSong() { return ts.getCurrentSong(); } 21 | public void setUser(User u) { this.user = u; } 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronization/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronization; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | MyObject obj1 = new MyObject(); 8 | MyObject obj2 = new MyObject(); 9 | MyClass thread1 = new MyClass(obj1, "1"); 10 | MyClass thread2 = new MyClass(obj2, "2"); 11 | 12 | thread1.start(); 13 | thread2.start(); 14 | 15 | Thread.sleep(3000 * 3); 16 | } catch (InterruptedException exc) { 17 | System.out.println("Program Interrupted."); 18 | } 19 | System.out.println("Program terminating."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question7_3; 2 | 3 | public class Question { 4 | public static int randomInt(int n) { 5 | return (int) (Math.random() * n); 6 | } 7 | 8 | public static void main(String[] args) { 9 | for (int i = 0; i < 10; i++) { 10 | Line line1 = new Line(randomInt(5), randomInt(1)); 11 | Line line2 = new Line(randomInt(5), randomInt(2)); 12 | line1.print(); 13 | System.out.print(", "); 14 | line2.print(); 15 | if (line1.intersect(line2)) { 16 | System.out.println(" YES"); 17 | } else { 18 | System.out.println(" NO"); 19 | } 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_8/rotation.py: -------------------------------------------------------------------------------- 1 | def isRotation(s1, s2): 2 | '''check if s1 is a rotation of s2''' 3 | if len(s1) != len(s2): 4 | return False 5 | 6 | if not s1 or not s2: 7 | return False 8 | 9 | return (s2 * 2).find(s1) != -1 10 | 11 | 12 | if __name__ == '__main__': 13 | words = ( ('erbottlewa', 'waterbottle'), 14 | ('erbottlewat', 'waterbottle'), 15 | ('copa', 'apoc'), 16 | ('nick', 'nik'), 17 | ('', ''), 18 | (' ', ' ') ) 19 | 20 | for w1, w2 in words: 21 | print('isRotation({}, {}): {}'.format(w1, w2, isRotation(w1, w2))) 22 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_3/questionB.dart: -------------------------------------------------------------------------------- 1 | 2 | int countFactZeros(int n) { 3 | int count = 0; 4 | if (n < 0) { 5 | print("Factorial is not defined for negative numbers"); 6 | return 0; 7 | } 8 | 9 | for (int i = 5; n ~/ i > 0; i *= 5) { 10 | count += n ~/ i; 11 | } 12 | 13 | return count; 14 | } 15 | 16 | int factorial(int n) { 17 | if (n == 1) { 18 | return 1; 19 | } else if (n > 1) { 20 | return n * factorial(n - 1); 21 | } else { 22 | return -1; // Error; 23 | } 24 | } 25 | 26 | void main() { 27 | for (int i = 0; i < 12; i++) { 28 | print("$i! (or ${factorial(i)}) has ${countFactZeros(i)} zeros"); 29 | } 30 | } -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/suit.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | class Suit { 4 | static const Club = 0; 5 | static const Diamond = 1; 6 | static const Heart = 2; 7 | static const Spade = 3; 8 | 9 | int _value; 10 | Suit(this._value); 11 | 12 | int get value => _value; 13 | 14 | static Suit getSuitFromValue(int value) { 15 | switch(value) { 16 | case 0: 17 | return new Suit(Suit.Club); 18 | case 1: 19 | return new Suit(Suit.Diamond); 20 | case 2: 21 | return new Suit(Suit.Heart); 22 | case 3: 23 | return new Suit(Suit.Spade); 24 | default: 25 | return null; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronizedBlocks/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronizedBlocks; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | MyObject obj1 = new MyObject(); 8 | MyObject obj2 = new MyObject(); 9 | 10 | MyClass thread1 = new MyClass(obj1, "1"); 11 | MyClass thread2 = new MyClass(obj1, "2"); 12 | 13 | thread1.start(); 14 | thread2.start(); 15 | 16 | Thread.sleep(3000 * 3); 17 | } catch (InterruptedException exc) { 18 | System.out.println("Program Interrupted."); 19 | } 20 | System.out.println("Program terminating."); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question16_4; 2 | 3 | public class Question { 4 | 5 | public static void main(String[] args) { 6 | int[] res1 = {1, 2, 3, 4}; 7 | int[] res2 = {1, 5, 4, 1}; 8 | int[] res3 = {1, 4, 5}; 9 | 10 | LockFactory.initialize(10); 11 | 12 | LockFactory lf = LockFactory.getInstance(); 13 | System.out.println(lf.declare(1, res1)); 14 | System.out.println(lf.declare(2, res2)); 15 | System.out.println(lf.declare(3, res3)); 16 | 17 | System.out.println(lf.getLock(1, 1)); 18 | System.out.println(lf.getLock(1, 2)); 19 | System.out.println(lf.getLock(2, 4)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 14/Question14_6/Question.java: -------------------------------------------------------------------------------- 1 | package Question14_6; 2 | 3 | public class Question { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | int size = 10; 10 | CircularArray array = new CircularArray(size); 11 | for (int i = 0; i < size; i++) { 12 | array.set(i, String.valueOf(i)); 13 | } 14 | 15 | array.rotate(3); 16 | for (int i = 0; i < size; i++) { 17 | System.out.println(array.get(i)); 18 | } 19 | 20 | System.out.println(""); 21 | 22 | array.rotate(2); 23 | for (String s : array) { 24 | System.out.println(s); 25 | } 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_10/Cell.java: -------------------------------------------------------------------------------- 1 | package Question8_10; 2 | 3 | public class Cell { 4 | private K key; 5 | private V value; 6 | public Cell(K k, V v) { 7 | key = k; 8 | value = v; 9 | } 10 | 11 | public boolean equivalent(Cell c) { 12 | return equivalent(c.getKey()); 13 | } 14 | 15 | public boolean equivalent(K k) { 16 | return key.equals(k); 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return "(" + key.toString() + ", " + value.toString() + ")"; 22 | } 23 | 24 | public K getKey() { 25 | return key; 26 | } 27 | 28 | public V getValue() { 29 | return value; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /dart/Chapter5/Question5_5/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int bitSwapRequired(int a, int b) { 3 | int count = 0; 4 | for (int c = a ^ b; c != 0; c = c >> 1) { 5 | count += c & 1; 6 | } 7 | 8 | return count; 9 | } 10 | 11 | int bitSwapRequired2(int a, int b) { 12 | int count = 0; 13 | for (int c = a ^ b; c != 0; c = c & (c - 1)) { 14 | count++; 15 | } 16 | 17 | return count; 18 | } 19 | 20 | void main() { 21 | int a = 23432; 22 | int b = 512132; 23 | print("$a: ${a.toRadixString(2)}"); 24 | print("$b: ${b.toRadixString(2)}"); 25 | int nbits = bitSwapRequired(a, b); 26 | int nbits2 = bitSwapRequired2(a, b); 27 | print("Required number of bits: $nbits $nbits2"); 28 | } -------------------------------------------------------------------------------- /dart/Chapter9/Question9_8/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int makeChange(int n, [int denom = 25]) { 3 | //print("$n $denom"); 4 | 5 | int next_denom = 0; 6 | switch(denom) { 7 | case 25: 8 | next_denom = 10; 9 | break; 10 | case 10: 11 | next_denom = 5; 12 | break; 13 | case 5: 14 | next_denom = 1; 15 | break; 16 | case 1: 17 | return 1; 18 | } 19 | 20 | int ways = 0; 21 | for (int i = 0; i * denom <= n; i++) { 22 | ways += makeChange(n - i * denom, next_denom); 23 | } 24 | 25 | return ways; 26 | } 27 | 28 | void main() { 29 | for (int i = 100; i >= 1; i--) { 30 | print("makeChange($i) = ${makeChange(i)}"); 31 | } 32 | } -------------------------------------------------------------------------------- /python/Chapter 2/Question2_4.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | def partition(linkedlist, x): 4 | if linkedlist.head != None: 5 | p1 = linkedlist.head 6 | p2 = linkedlist.head.next 7 | while p2 != None: 8 | if p2.value < x: 9 | p1.next = p2.next 10 | p2.next = linkedlist.head 11 | linkedlist.head = p2 12 | p2 = p1.next 13 | else: 14 | p1 = p1.next 15 | p2 = p1.next 16 | 17 | 18 | 19 | #----------------test----------------- 20 | L = randomLinkedList(10, 0, 50) 21 | x = 25 22 | 23 | print L, " , x=25" 24 | partition(L, x) 25 | print L 26 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_3/questionA.dart: -------------------------------------------------------------------------------- 1 | 2 | int factorsOf5(int i) { 3 | int count = 0; 4 | while (i % 5 == 0) { 5 | count++; 6 | i ~/= 5; 7 | } 8 | return count; 9 | } 10 | 11 | int countFactZeros(int n) { 12 | int count = 0; 13 | for (int i = 2; i <= n; i++) { 14 | count += factorsOf5(i); 15 | } 16 | 17 | return count; 18 | } 19 | 20 | int factorial(int n) { 21 | if (n == 1) { 22 | return 1; 23 | } else if (n > 1) { 24 | return n * factorial(n - 1); 25 | } else { 26 | return -1; // Error; 27 | } 28 | } 29 | 30 | void main() { 31 | for (int i = 1; i < 12; i++) { 32 | print("$i! (or ${factorial(i)}) has ${countFactZeros(i)} zeros"); 33 | } 34 | } -------------------------------------------------------------------------------- /python/Chapter 1/Question1_2/ChapQ1.2.py: -------------------------------------------------------------------------------- 1 | #Implement a function that reverses a string 2 | 3 | #using recursion here to avoid recopying the string, as described in the discussion of "string buffer". 4 | 5 | def reverseStringRecursive(str1): 6 | if str1 != "": 7 | return str1[-1:] + reverseStringRecursive(str1[:-1]) 8 | else: 9 | return "" 10 | 11 | #testing 12 | 13 | palindrome = "abcdedcba" 14 | nonpalindrome = "hello!" 15 | 16 | #palindrome can be reversed and would still be equal to itself, by definition. 17 | if palindrome == reverseStringRecursive(palindrome): 18 | print "Test 1 passed" 19 | if nonpalindrome != reverseStringRecursive(nonpalindrome): 20 | print "Test 2 passed" 21 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_1/alluniq.py: -------------------------------------------------------------------------------- 1 | def allunique(s): 2 | charsTable = set() 3 | for c in s: 4 | if c in charsTable: 5 | return False 6 | charsTable.add(c) 7 | return True 8 | 9 | def pairs(seq): 10 | n = len(seq) 11 | for i in range(n): 12 | yield seq[i], seq[(i + 1) % n] 13 | 14 | def allunique2(s): 15 | srtStr = sorted(s) 16 | for (c1, c2) in pairs(srtStr): 17 | if c1 == c2: 18 | return False 19 | return True 20 | 21 | if __name__ == '__main__': 22 | words = ('mary', 'ariadni') 23 | for w in words: 24 | print('allunique({}): {}'.format(w, allunique(w))) 25 | print('allunique2({}): {}'.format(w, allunique2(w))) 26 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/AddRequest.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | import java.util.Date; 4 | 5 | public class AddRequest { 6 | private User fromUser; 7 | private User toUser; 8 | private Date date; 9 | RequestStatus status; 10 | 11 | public AddRequest(User from, User to, Date date) { 12 | fromUser = from; 13 | toUser = to; 14 | this.date = date; 15 | status = RequestStatus.Unread; 16 | } 17 | 18 | public RequestStatus getStatus() { 19 | return status; 20 | } 21 | 22 | public User getFromUser() { 23 | return fromUser; 24 | } 25 | 26 | public User getToUser() { 27 | return toUser; 28 | } 29 | 30 | public Date getDate() { 31 | return date; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_2/Person.java: -------------------------------------------------------------------------------- 1 | package Question10_2; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Person { 6 | private ArrayList friends; 7 | private int personID; 8 | private String info; 9 | 10 | public String getInfo() { return info; } 11 | public void setInfo(String info) { 12 | this.info = info; 13 | } 14 | 15 | public int[] getFriends() { 16 | int[] temp = new int[friends.size()]; 17 | for (int i = 0; i < temp.length; i++) { 18 | temp[i] = friends.get(i); 19 | } 20 | return temp; 21 | } 22 | public int getID() { return personID; } 23 | public void addFriend(int id) { friends.add(id); } 24 | 25 | public Person(int id) { 26 | this.personID = id; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/StackWithMin2.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackWithMin2 extends Stack { 6 | Stack s2; 7 | 8 | public StackWithMin2() { 9 | s2 = new Stack(); 10 | } 11 | 12 | public void push(int value){ 13 | if (value <= min()) { 14 | s2.push(value); 15 | } 16 | super.push(value); 17 | } 18 | 19 | public Integer pop() { 20 | int value = super.pop(); 21 | if (value == min()) { 22 | s2.pop(); 23 | } 24 | return value; 25 | } 26 | 27 | public int min() { 28 | if (s2.isEmpty()) { 29 | return Integer.MAX_VALUE; 30 | } else { 31 | return s2.peek(); 32 | } 33 | } 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /java/Chapter 7/Introduction/PrimeNumbers.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class PrimeNumbers { 4 | 5 | public static boolean primeNaive(int n) { 6 | for (int i = 2; i < n; i++) { 7 | if (n % i == 0) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | public static boolean primeSlightlyBetter(int n) { 15 | int sqrt = (int) Math.sqrt(n); 16 | for (int i = 2; i <= sqrt; i++) { 17 | if (n % i == 0) { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | public static void main(String[] args) { 25 | for (int i = 2; i < 100; i++) { 26 | if (primeSlightlyBetter(i)) { 27 | System.out.println(i); 28 | } 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | public static void main(String[] args) { 7 | StackWithMin stack = new StackWithMin(); 8 | StackWithMin2 stack2 = new StackWithMin2(); 9 | for (int i = 0; i < 15; i++) { 10 | int value = AssortedMethods.randomIntInRange(0, 100); 11 | stack.push(value); 12 | stack2.push(value); 13 | System.out.print(value + ", "); 14 | } 15 | System.out.println('\n'); 16 | for (int i = 0; i < 15; i++) { 17 | System.out.println("Popped " + stack.pop().value + ", " + stack2.pop()); 18 | System.out.println("New min is " + stack.min() + ", " + stack2.min()); 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/Library.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | import java.util.Hashtable; 4 | 5 | public class Library { 6 | 7 | private Hashtable books; 8 | 9 | public Book addBook(int id, String details) { 10 | if (books.containsKey(id)) { 11 | return null; 12 | } 13 | Book book = new Book(id, details); 14 | books.put(id, book); 15 | return book; 16 | } 17 | 18 | public boolean remove(Book b){ 19 | return remove(b.getID()); 20 | } 21 | 22 | public boolean remove(int id) { 23 | if (!books.containsKey(id)) { 24 | return false; 25 | } 26 | books.remove(id); 27 | return true; 28 | } 29 | 30 | public Book find(int id){ 31 | return books.get(id); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_4/QuestionBrute.java: -------------------------------------------------------------------------------- 1 | package Question18_4; 2 | 3 | public class QuestionBrute { 4 | 5 | public static int numberOf2s(int n) { 6 | int count = 0; 7 | while (n > 0) { 8 | if (n % 10 == 2) { 9 | count++; 10 | } 11 | n = n / 10; 12 | } 13 | return count; 14 | } 15 | 16 | public static int numberOf2sInRange(int n) { 17 | int count = 0; 18 | for (int i = 2; i <= n; i++) { // Might as well start at 2 19 | count += numberOf2s(i); 20 | } 21 | return count; 22 | } 23 | 24 | public static void main(String[] args) { 25 | for (int i = 0; i < 1000; i++) { 26 | int v = numberOf2sInRange(i); 27 | System.out.println("Between 0 and " + i + ": " + v); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question10_4; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | 7 | public static void checkDuplicates(int[] array) { 8 | BitSet bs = new BitSet(32000); 9 | for (int i = 0; i < array.length; i++) { 10 | int num = array[i]; 11 | int num0 = num - 1; // bitset starts at 0, numbers start at 1 12 | if (bs.get(num0)) { 13 | System.out.println(num); 14 | } else { 15 | bs.set(num0); 16 | } 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] array = AssortedMethods.randomArray(30, 1, 30); 22 | System.out.println(AssortedMethods.arrayToString(array)); 23 | checkDuplicates(array); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question2_3; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | import CtCILibrary.LinkedListNode; 5 | 6 | public class Question { 7 | 8 | public static boolean deleteNode(LinkedListNode n) { 9 | if (n == null || n.next == null) { 10 | return false; // Failure 11 | } 12 | LinkedListNode next = n.next; 13 | n.data = next.data; 14 | n.next = next.next; 15 | return true; 16 | } 17 | 18 | public static void main(String[] args) { 19 | LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10); 20 | System.out.println(head.printForward()); 21 | deleteNode(head.next.next.next.next); // delete node 4 22 | System.out.println(head.printForward()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /python/Chapter 2/Question2_2.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | 4 | # if k = 1, return the last element 5 | def kth_to_last(linkedlist, k): 6 | if k <= 0: 7 | return "invalid k" 8 | pointer2 = linkedlist.head 9 | for i in range(k-1): 10 | if pointer2.next != None: 11 | pointer2 = pointer2.next 12 | else: 13 | return "k exceeds the length of linkedlist" 14 | pointer1 = linkedlist.head 15 | while pointer2.next != None: 16 | pointer2 = pointer2.next 17 | pointer1 = pointer1.next 18 | return pointer1 19 | 20 | 21 | 22 | #---------------test------------------ 23 | L = randomLinkedList(8, 0, 100) 24 | print L 25 | print "The 3th to last element is", kth_to_last(L, 3) 26 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_12/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_12; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Question { 6 | public static void printPairSums(int[] array, int sum) { 7 | Arrays.sort(array); 8 | int first = 0; 9 | int last = array.length - 1; 10 | while (first < last) { 11 | int s = array[first] + array[last]; 12 | if (s == sum) { 13 | System.out.println(array[first] + " " + array[last]); 14 | ++first; 15 | --last; 16 | } else { 17 | if (s < sum) { 18 | ++first; 19 | } else { 20 | --last; 21 | } 22 | } 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] test = {9, 3, 6, 5, 7, -1, 13, 14, -2, 12, 0}; 28 | printPairSums(test, 12); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/UserManager.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | import java.util.Hashtable; 4 | 5 | public class UserManager { 6 | private Hashtable users; 7 | 8 | public User addUser(int id, String details, int accountType) { 9 | if (users.containsKey(id)) { 10 | return null; 11 | } 12 | User user = new User(id, details, accountType); 13 | users.put(id, user); 14 | return user; 15 | } 16 | 17 | public boolean remove(User u) { 18 | return remove(u.getID()); 19 | } 20 | 21 | public boolean remove(int id) { 22 | if (!users.containsKey(id)) { 23 | return false; 24 | } 25 | users.remove(id); 26 | return true; 27 | } 28 | 29 | public User find(int id){ 30 | return users.get(id); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_11/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | int rand7() { 6 | while(true) { 7 | int n = 5 * rand5() + rand5(); 8 | if (n < 21) { 9 | return n % 7; 10 | } 11 | } 12 | } 13 | 14 | int rand5() { 15 | return ((random.nextDouble() * 100) % 5).toInt(); 16 | } 17 | 18 | void main() { 19 | /* 20 | * Test: call rand7 many times and inspect the results; 21 | */ 22 | List arr = new List.fixedLength(7, fill: 0); 23 | 24 | int test_size = 1000000; 25 | for (int k = 0; k < test_size; k++) { 26 | arr[rand7()]++; 27 | } 28 | 29 | for (int i = 0; i < 7; i++) { 30 | double percent = 100.0 * arr[i] / test_size; 31 | print ("$i appeared $percent% of the time."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dart/Chapter4/Question4_5/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/tree_node.dart'; 2 | 3 | int last_printed = 0; // minimum value our ints can have. 4 | 5 | bool checkBST(TreeNode n) { 6 | if (n == null) { 7 | return true; 8 | } 9 | 10 | // Check / recurse left 11 | if (!checkBST(n.left)) { 12 | return false; 13 | } 14 | 15 | // Check current 16 | if (n.data < last_printed) { 17 | return false; 18 | } 19 | 20 | last_printed = n.data; 21 | 22 | // Check /recurse right 23 | if (!checkBST(n.right)) { 24 | return false; 25 | } 26 | 27 | return true; 28 | } 29 | 30 | void main() { 31 | List array = [3, 5, 7, 10, 13, 15, 20]; 32 | TreeNode node = TreeNode.createMinimalBST(array); 33 | //node.left.right.data = 3; 34 | print(checkBST(node)); 35 | } -------------------------------------------------------------------------------- /dart/Chapter17/Question17_2/question.dart: -------------------------------------------------------------------------------- 1 | int convertBoardToInt(List> board) { 2 | int factor = 1; 3 | int sum = 0; 4 | for (int i = 0; i < board.length; i++) { 5 | for (int j = 0; j < board[i].length; j++) { 6 | int v = 0; 7 | if (board[i][j] == 'x') { 8 | v = 1; 9 | } else if (board[i][j] == 'o') { 10 | v = 2; 11 | } 12 | 13 | sum += v * factor; 14 | factor *= 3; 15 | } 16 | } 17 | 18 | return sum; 19 | } 20 | 21 | void main() { 22 | List> board = [ 23 | ['x', 'x', 'o'], 24 | [' ', 'x', ' '], 25 | [' ', ' ', 'x'] 26 | ]; 27 | int v = convertBoardToInt(board); 28 | print(v); 29 | } -------------------------------------------------------------------------------- /java/Chapter 9/Question9_10/Box.java: -------------------------------------------------------------------------------- 1 | package Question9_10; 2 | 3 | public class Box { 4 | public int width; 5 | public int height; 6 | public int depth; 7 | public Box(int w, int h, int d) { 8 | width = w; 9 | height = h; 10 | depth = d; 11 | } 12 | 13 | public boolean canBeUnder(Box b) { 14 | if (width > b.width && height > b.height && depth > b.depth) { 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | public boolean canBeAbove(Box b) { 21 | if (b == null) { 22 | return true; 23 | } 24 | if (width < b.width && height < b.height && depth < b.depth) { 25 | return true; 26 | } 27 | return false; 28 | } 29 | 30 | public String toString() { 31 | return "Box(" + width + "," + height + "," + depth + ")"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dart/Chapter7/Question7_3/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | class Line { 4 | static double epsilon = 0.000001; 5 | double slope; 6 | double yintercept; 7 | Line(this.slope, this.yintercept); 8 | String print_line() => "y = ${slope}x + $yintercept"; 9 | bool intersect(Line line2) => (slope - line2.slope).abs() > epsilon || (yintercept - line2.yintercept).abs() < epsilon; 10 | } 11 | 12 | int randomInt(int n) => (new Random().nextDouble() * n).toInt(); 13 | 14 | void main() { 15 | for (int i = 0; i < 10; i++) { 16 | Line line1 = new Line(randomInt(5).toDouble(), randomInt(1).toDouble()); 17 | Line line2 = new Line(randomInt(5).toDouble(), randomInt(2).toDouble()); 18 | print("${line1.print_line()}, ${line2.print_line()} ${line1.intersect(line2) ? 'YES' : 'NO' }"); 19 | } 20 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | 7 | /** 8 | * @param args 9 | */ 10 | public static void main(String[] args) { 11 | ParkingLot lot = new ParkingLot(); 12 | 13 | Vehicle v = null; 14 | while (v == null || lot.parkVehicle(v)) { 15 | lot.print(); 16 | int r = AssortedMethods.randomIntInRange(0, 10); 17 | if (r < 2) { 18 | v = new Bus(); 19 | } else if (r < 4) { 20 | v = new Motorcycle(); 21 | } else { 22 | v = new Car(); 23 | } 24 | System.out.print("\nParking a "); 25 | v.print(); 26 | System.out.println(""); 27 | } 28 | System.out.println("Parking Failed. Final state: "); 29 | lot.print(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /python/Chapter 3/Question3_6/ChapQ3.6.py: -------------------------------------------------------------------------------- 1 | class Stack(list): 2 | def peak(self): 3 | return self[-1] 4 | def push(self, item): 5 | self.append(item) 6 | def empty(self): 7 | return len(self) == 0 8 | 9 | def sort_stack(s): 10 | r = Stack() 11 | while not s.empty(): 12 | tmp = s.pop() 13 | while not r.empty() and r.peak() > tmp: 14 | s.push(r.pop()) 15 | r.push(tmp) 16 | while not s.empty() and s.peak() >= r.peak(): 17 | #warning, >= here 18 | r.push(s.pop()) 19 | return r 20 | 21 | #testing 22 | from random import randrange 23 | test_items = [randrange(20) for x in xrange(20)] 24 | print test_items 25 | S = Stack() 26 | for item in test_items: 27 | S.push(item) 28 | S = Stack.sort_stack(S) 29 | for i, item in enumerate(sorted(test_items)): 30 | print "item", item, S[i] 31 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_2/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_2; 2 | 3 | public class Question { 4 | 5 | public static int convertBoardToInt(char[][] board) { 6 | int factor = 1; 7 | int sum = 0; 8 | for (int i = 0; i < board.length; i++) { 9 | for (int j = 0; j < board[i].length; j++) { 10 | int v = 0; 11 | if (board[i][j] == 'x') { 12 | v = 1; 13 | } else if (board[i][j] == 'o') { 14 | v = 2; 15 | } 16 | sum += v * factor; 17 | factor *= 3; 18 | } 19 | } 20 | return sum; 21 | } 22 | 23 | public static void main(String[] args) { 24 | char[][] board = { 25 | {'x', 'x', 'o'}, 26 | {' ', 'x', ' '}, 27 | {' ', ' ', 'x'}}; 28 | 29 | int v = convertBoardToInt(board); 30 | System.out.println(v); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/User.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | public class User { 4 | private int userId; 5 | private String details; 6 | private int accountType; 7 | 8 | public void renewMembership() { } 9 | 10 | public User(int id, String details, int accountType) { 11 | userId = id; 12 | this.details = details; 13 | this.accountType = accountType; 14 | } 15 | 16 | /* getters and setters */ 17 | public int getID() { return userId; } 18 | public void setID(int id) { userId = id; } 19 | public String getDetails() { return details; } 20 | public void setDetails(String details) { this.details = details; } 21 | public int getAccountType() { return accountType; } 22 | public void setAccountType(int accountType) { 23 | this.accountType = accountType; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_11/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_11; 2 | 3 | public class Question { 4 | public static int rand7() { 5 | while (true) { 6 | int num = 5 * rand5() + rand5(); 7 | if (num < 21) { 8 | return num % 7; 9 | } 10 | } 11 | } 12 | 13 | public static int rand5() { 14 | return (int) (Math.random() * 100) % 5; 15 | } 16 | 17 | public static void main(String[] args) { 18 | /* Test: call rand7 many times and inspect the results. */ 19 | int[] arr = new int[7]; 20 | int test_size = 1000000; 21 | for(int k = 0; k < test_size; k++){ 22 | arr[rand7()]++; 23 | } 24 | 25 | for (int i = 0; i < 7; i++) { 26 | double percent = 100.0 * arr[i] / test_size; 27 | System.out.println(i + " appeared " + percent + "% of the time."); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_2/Question1_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Question1_2.h" 3 | 4 | using std::cout; 5 | using std::endl; 6 | 7 | void Question1_2::reverse(char* str) { 8 | char *ptrEnd = str; 9 | char temp; 10 | if(str) { 11 | while(*ptrEnd) { 12 | ptrEnd++; 13 | } 14 | ptrEnd--; 15 | 16 | while(str < ptrEnd) { 17 | temp = *str; 18 | *str++ = *ptrEnd; 19 | *ptrEnd-- = temp; 20 | } 21 | } 22 | } 23 | 24 | int Question1_2::run() { 25 | char input[][10] ={"abcde", "cat"}; 26 | for(int i = 0; i < 2; i++) { 27 | cout << "reversing the string: " << input[i] << endl; 28 | reverse(input[i]); 29 | cout << "reverse of input string is " << input[i] << endl; 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_1/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_1; 2 | 3 | public class Question { 4 | 5 | public static void swap(int a, int b) { 6 | // Example for a = 9, b = 4 7 | a = a - b; // a = 9 - 4 = 5 8 | b = a + b; // b = 5 + 4 = 9 9 | a = b - a; // a = 9 - 5 10 | 11 | System.out.println("a: " + a); 12 | System.out.println("b: " + b); 13 | } 14 | 15 | public static void swap_opt(int a, int b) { 16 | a = a^b; 17 | b = a^b; 18 | a = a^b; 19 | 20 | System.out.println("a: " + a); 21 | System.out.println("b: " + b); 22 | } 23 | 24 | public static void main(String[] args) { 25 | int a = 1672; 26 | int b = 9332; 27 | 28 | System.out.println("a: " + a); 29 | System.out.println("b: " + b); 30 | 31 | swap(a, b); 32 | swap_opt(a, b); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /dart/Chapter1/Question1_2/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement a function void reverse(char* str) in C or C++ 3 | * which reverses a null-terminated string 4 | */ 5 | 6 | /* This is a classic interview question. 7 | * The only "gotcha" is to try to do it inplace, 8 | * and be careful for the null character. 9 | */ 10 | /* 11 | void reverse(char *str) { 12 | char* end = str; 13 | char tmp; 14 | if (str) { 15 | while (*end) { /* find end of the string */ 16 | ++end; 17 | } 18 | 19 | --end; /* set one char back, since last char is null */ 20 | 21 | /* 22 | * swap characters from start of string with the end of 23 | * the string, until the pointers meet in the middle. 24 | */ 25 | while (str < end) { 26 | tmp = *str; 27 | *str++ = *end; 28 | *end-- = tmp; 29 | } 30 | } 31 | } 32 | */ -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/black_jack_card.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | class BlackJackCard extends Card { 4 | BlackJackCard(int c, Suit s) : super(c, s); 5 | 6 | int value() { 7 | if (isAce()) { // Ace 8 | return 1; 9 | } else if (faceValue >= 11 && faceValue <= 13) { // Face card 10 | return 10; 11 | } else { // Number card 12 | return faceValue; 13 | } 14 | } 15 | 16 | int minValue() { 17 | if (isAce()) { // Ace 18 | return 1; 19 | } else { 20 | return value(); 21 | } 22 | } 23 | 24 | int maxValue() { 25 | if (isAce()) { // Ace 26 | return 11; 27 | } else { 28 | return value(); 29 | } 30 | } 31 | 32 | bool isAce() { 33 | return faceValue == 1; 34 | } 35 | 36 | bool isFaceCard() { 37 | return faceValue >= 11 && faceValue <= 13; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Game.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | import java.util.ArrayList; 4 | 5 | import CtCILibrary.AssortedMethods; 6 | 7 | public class Game { 8 | private Player[] players; 9 | private static Game instance; 10 | private Board board; 11 | private final int ROWS = 10; 12 | private final int COLUMNS = 10; 13 | 14 | private Game() { 15 | board = new Board(ROWS, COLUMNS); 16 | players = new Player[2]; 17 | players[0] = new Player(Color.Black); 18 | players[1] = new Player(Color.White); 19 | Automator.getInstance().initialize(players); // used for testing 20 | } 21 | 22 | public static Game getInstance() { 23 | if (instance == null) { 24 | instance = new Game(); 25 | } 26 | return instance; 27 | } 28 | 29 | public Board getBoard() { 30 | return board; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronization/MyObject.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronization; 2 | 3 | public class MyObject { 4 | public static synchronized void foo(String name) { 5 | try { 6 | System.out.println("Thread " + name + ".foo(): starting"); 7 | Thread.sleep(3000); 8 | System.out.println("Thread " + name + ".foo(): ending"); 9 | } catch (InterruptedException exc) { 10 | System.out.println("Thread " + name + ": interrupted."); 11 | } 12 | } 13 | 14 | public static synchronized void bar(String name) { 15 | try { 16 | System.out.println("Thread " + name + ".bar(): starting"); 17 | Thread.sleep(3000); 18 | System.out.println("Thread " + name + ".bar(): ending"); 19 | } catch (InterruptedException exc) { 20 | System.out.println("Thread " + name + ": interrupted."); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_3/QuestionB.java: -------------------------------------------------------------------------------- 1 | package Question17_3; 2 | 3 | public class QuestionB { 4 | public static int countFactZeros(int num) { 5 | int count = 0; 6 | if (num < 0) { 7 | System.out.println("Factorial is not defined for negative numbers"); 8 | return 0; 9 | } 10 | for (int i = 5; num / i > 0; i *= 5) { 11 | count += num / i; 12 | } 13 | return count; 14 | } 15 | 16 | public static int factorial(int num) { 17 | if (num == 1) { 18 | return 1; 19 | } else if (num > 1) { 20 | return num * factorial(num - 1); 21 | } else { 22 | return -1; // Error 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | for (int i = 1; i < 12; i++) { 28 | System.out.println(i + "! (or " + factorial(i) + ") has " + countFactZeros(i) + " zeros"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_1/StackData.java: -------------------------------------------------------------------------------- 1 | package Question3_1; 2 | 3 | public class StackData { 4 | public int start; 5 | public int pointer; 6 | public int size = 0; 7 | public int capacity; 8 | public StackData(int _start, int _capacity) { 9 | start = _start; 10 | pointer = _start - 1; 11 | capacity = _capacity; 12 | } 13 | 14 | public boolean isWithinStack(int index, int total_size) { 15 | // Note: if stack wraps, the head (right side) wraps around to the left. 16 | if (start <= index && index < start + capacity) { 17 | // non-wrapping, or "head" (right side) of wrapping case 18 | return true; 19 | } else if (start + capacity > total_size && 20 | index < (start + capacity) % total_size) { 21 | // tail (left side) of wrapping case 22 | return true; 23 | } 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /dart/Chapter2/Question2_3/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement an algorithm to delete a node in the middle of a 3 | * singly linked list, given only access to that node. 4 | * EXAMPLE 5 | * Input: the node c from the linked list a->b->c->d->e 6 | * Result: nothing is returned, but the new linked list looks like 7 | * a->b->d->e 8 | */ 9 | import '../../utils/linked_list_node.dart'; 10 | import '../../utils/assorted_methods.dart'; 11 | 12 | bool deleteNode(LinkedListNode n) { 13 | if (n == null || n.next == null) { 14 | return false; // Failure 15 | } 16 | 17 | LinkedListNode next = n.next; 18 | n.data = next.data; 19 | n.next = next.next; 20 | return true; 21 | } 22 | 23 | void main() { 24 | LinkedListNode head = randomLinkedList(10, 0, 10); 25 | print(head.printFoward()); 26 | deleteNode(head.next.next.next.next); 27 | print(head.printFoward()); 28 | } -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/IntroductionOverriding.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class IntroductionOverriding { 4 | 5 | public static void printArea(Circle c) { 6 | System.out.println("The circle is " + c.computeArea()); 7 | } 8 | 9 | public static void printArea(Square s) { 10 | System.out.println("The square is " + s.computeArea()); 11 | } 12 | 13 | public static void printArea(Ambiguous s) { 14 | System.out.println("The ambiguous is undefined"); 15 | } 16 | 17 | public static void main(String[] args) { 18 | Shape[] shapes = new Shape[2]; 19 | Circle circle = new Circle(); 20 | Ambiguous ambiguous = new Ambiguous(); 21 | 22 | shapes[0] = circle; 23 | shapes[1] = ambiguous; 24 | 25 | for (Shape s : shapes) { 26 | s.printMe(); 27 | System.out.println(s.computeArea()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question16_3; 2 | 3 | public class Question { 4 | public static int size = 3; 5 | 6 | public static int leftOf(int i) { 7 | return i; 8 | } 9 | 10 | public static int rightOf(int i) { 11 | return (i + 1) % size; 12 | } 13 | 14 | public static void main(String[] args) { 15 | Chopstick[] chopsticks = new Chopstick[size + 1]; 16 | for (int i = 0; i < size + 1; i++) { 17 | chopsticks[i] = new Chopstick(); 18 | } 19 | 20 | Philosopher[] philosophers = new Philosopher[size]; 21 | for (int i = 0; i < size; i++) { 22 | Chopstick left = chopsticks[leftOf(i)]; 23 | Chopstick right = chopsticks[rightOf(i)]; 24 | philosophers[i] = new Philosopher(i, left, right); 25 | } 26 | 27 | for (int i = 0; i < size; i++) { 28 | philosophers[i].start(); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_2/Node.java: -------------------------------------------------------------------------------- 1 | package Question4_2; 2 | 3 | class Node { 4 | private Node adjacent[]; 5 | public int adjacentCount; 6 | private String vertex; 7 | public Question.State state; 8 | public Node(String vertex, int adjacentLength) { 9 | this.vertex = vertex; 10 | adjacentCount = 0; 11 | adjacent = new Node[adjacentLength]; 12 | } 13 | 14 | public void addAdjacent(Node x) { 15 | if (adjacentCount < 30) { 16 | this.adjacent[adjacentCount] = x; 17 | adjacentCount++; 18 | } else { 19 | System.out.print("No more adjacent can be added"); 20 | } 21 | } 22 | public Node[] getAdjacent() { 23 | return adjacent; 24 | } 25 | public String getVertex() { 26 | return vertex; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_6/Coordinate.java: -------------------------------------------------------------------------------- 1 | package Question11_6; 2 | 3 | public class Coordinate implements Cloneable { 4 | public int row; 5 | public int column; 6 | public Coordinate(int r, int c) { 7 | row = r; 8 | column = c; 9 | } 10 | 11 | public boolean inbounds(int[][] matrix) { 12 | return row >= 0 && 13 | column >= 0 && 14 | row < matrix.length && 15 | column < matrix[0].length; 16 | } 17 | 18 | public boolean isBefore(Coordinate p) { 19 | return row <= p.row && column <= p.column; 20 | } 21 | 22 | public Object clone() { 23 | return new Coordinate(row, column); 24 | } 25 | 26 | public void moveDownRight() { 27 | row++; 28 | column++; 29 | } 30 | 31 | public void setToAverage(Coordinate min, Coordinate max) { 32 | row = (min.row + max.row) / 2; 33 | column = (min.column + max.column) / 2; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/ParkingLot.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class ParkingLot { 4 | private Level[] levels; 5 | private final int NUM_LEVELS = 5; 6 | 7 | public ParkingLot() { 8 | levels = new Level[NUM_LEVELS]; 9 | for (int i = 0; i < NUM_LEVELS; i++) { 10 | levels[i] = new Level(i, 30); 11 | } 12 | } 13 | 14 | /* Park the vehicle in a spot (or multiple spots). Return false if failed. */ 15 | public boolean parkVehicle(Vehicle vehicle) { 16 | for (int i = 0; i < levels.length; i++) { 17 | if (levels[i].parkVehicle(vehicle)) { 18 | return true; 19 | } 20 | } 21 | return false; 22 | } 23 | 24 | public void print() { 25 | for (int i = 0; i < levels.length; i++) { 26 | System.out.print("Level" + i + ": "); 27 | levels[i].print(); 28 | System.out.println(""); 29 | } 30 | System.out.println(""); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dart/Chapter7/Question7_7/questionA.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | int removeMin(Queue q) { 4 | int min = q.first; 5 | for (int v in q) { 6 | if (min > v) { 7 | min = v; 8 | } 9 | } 10 | while (q.contains(min)) { 11 | q.removeFirst(); 12 | } 13 | 14 | return min; 15 | } 16 | 17 | void addProducts(Queue q, int v) { 18 | q.add(v * 3); 19 | q.add(v * 5); 20 | q.add(v * 7); 21 | } 22 | 23 | int getKthMagicNumber(int k) { 24 | if (k < 0) { 25 | return 0; 26 | } 27 | 28 | int val = 1; 29 | Queue q = new Queue(); 30 | addProducts(q, 1); 31 | for (int i = 0; i < k; i++) { // Start at 1 since we've already done one iteration 32 | val = removeMin(q); 33 | addProducts(q, val); 34 | } 35 | return val; 36 | } 37 | 38 | void main() { 39 | 40 | for(int i = 0; i < 14; i++) { 41 | print("$i : ${getKthMagicNumber(i)}"); 42 | } 43 | } -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionLocks/NoLockATM.java: -------------------------------------------------------------------------------- 1 | package IntroductionLocks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class NoLockATM { 7 | private int balance = 100; 8 | 9 | public NoLockATM() { 10 | } 11 | 12 | public int withdraw(int value) { 13 | int temp = balance; 14 | try { 15 | Thread.sleep(300); 16 | temp = temp - value; 17 | Thread.sleep(300); 18 | balance = temp; 19 | } catch (InterruptedException e) { } 20 | return temp; 21 | } 22 | 23 | public int deposit(int value) { 24 | int temp = balance; 25 | try { 26 | Thread.sleep(300); 27 | temp = temp + value; 28 | Thread.sleep(300); 29 | balance = temp; 30 | } catch (InterruptedException e) { } 31 | return temp; 32 | } 33 | 34 | public int getBalance() { 35 | return balance; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_3/QuestionA.java: -------------------------------------------------------------------------------- 1 | package Question17_3; 2 | 3 | public class QuestionA { 4 | public static int factorsOf5(int i) { 5 | int count = 0; 6 | while (i % 5 == 0) { 7 | count++; 8 | i /= 5; 9 | } 10 | return count; 11 | } 12 | 13 | public static int countFactZeros(int num) { 14 | int count = 0; 15 | for (int i = 2; i <= num; i++) { 16 | count += factorsOf5(i); 17 | } 18 | return count; 19 | } 20 | 21 | public static int factorial(int num) { 22 | if (num == 1) { 23 | return 1; 24 | } else if (num > 1) { 25 | return num * factorial(num - 1); 26 | } else { 27 | return -1; // Error 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | for (int i = 1; i < 12; i++) { 33 | System.out.println(i + "! (or " + factorial(i) + ") has " + countFactZeros(i) + " zeros"); 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_6/Foo.java: -------------------------------------------------------------------------------- 1 | package Question16_6; 2 | 3 | public class Foo { 4 | private String name; 5 | 6 | public Foo(String nm) { 7 | name = nm; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void pause() { 15 | try { 16 | Thread.sleep(1000 * 3); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | 22 | public synchronized void methodA(String threadName) { 23 | System.out.println("thread " + threadName + " starting: " + name + ".methodA()"); 24 | pause(); 25 | System.out.println("thread " + threadName + " ending: " + name + ".methodA()"); 26 | } 27 | 28 | public void methodB(String threadName) { 29 | System.out.println("thread " + threadName + " starting: " + name + ".methodB()"); 30 | pause(); 31 | System.out.println("thread " + threadName + " ending: " + name + ".methodB()"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_1/BlackJackCard.java: -------------------------------------------------------------------------------- 1 | package Question8_1; 2 | 3 | public class BlackJackCard extends Card { 4 | public BlackJackCard(int c, Suit s) { 5 | super(c, s); 6 | } 7 | 8 | public int value() { 9 | if (isAce()) { // Ace 10 | return 1; 11 | } else if (faceValue >= 11 && faceValue <= 13) { // Face card 12 | return 10; 13 | } else { // Number card 14 | return faceValue; 15 | } 16 | } 17 | 18 | public int minValue() { 19 | if (isAce()) { // Ace 20 | return 1; 21 | } else { 22 | return value(); 23 | } 24 | } 25 | 26 | public int maxValue() { 27 | if (isAce()) { // Ace 28 | return 11; 29 | } else { 30 | return value(); 31 | } 32 | } 33 | 34 | public boolean isAce() { 35 | return faceValue == 1; 36 | } 37 | 38 | public boolean isFaceCard() { 39 | return faceValue >= 11 && faceValue <= 13; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /dart/Chapter9/Introduction/fibonacci.dart: -------------------------------------------------------------------------------- 1 | int fibonacci(int i) { 2 | if (i == 0) { 3 | return 0; 4 | } 5 | 6 | if (i == 1) { 7 | return 1; 8 | } 9 | 10 | return fibonacci(i - 1) + fibonacci(i - 2); 11 | } 12 | 13 | void main() { 14 | int max = 35; // WARNING: If you make this above 40ish, your computer may serious slow down 15 | int trials = 10; // Run code multiple times to compute average time. 16 | List times = new List(max); 17 | for (int i = 0; i < times.length; i++) { 18 | times[i]=0; 19 | } 20 | Stopwatch sw = new Stopwatch(); 21 | 22 | for (int j = 0; j < trials; j++) { // Run this 10 times to compute 23 | for (int i = 0; i < max; i++) { 24 | sw.start(); 25 | fibonacci(i); 26 | sw.stop(); 27 | times[i] += sw.elapsedMilliseconds; 28 | } 29 | } 30 | 31 | for (int j = 0; j < max; j++) { 32 | print("$j: ${times[j]/trials}ms"); 33 | } 34 | } -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Introduction.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Introduction { 4 | public static String lem() { 5 | System.out.println("lem"); 6 | return "return from lem"; 7 | } 8 | 9 | public static String foo() { 10 | int x = 0; 11 | int y = 5; 12 | try 13 | { 14 | System.out.println("start try"); 15 | int b = y / x; 16 | System.out.println("end try"); 17 | return "returned from try"; 18 | } catch (Exception ex) { 19 | System.out.println("catch"); 20 | return lem() + " | returned from catch"; 21 | } finally { 22 | System.out.println("finally"); 23 | } 24 | } 25 | 26 | public static void bar() { 27 | System.out.println("start bar"); 28 | String v = foo(); 29 | System.out.println(v); 30 | System.out.println("end bar"); 31 | } 32 | 33 | public static void main(String[] args) { 34 | bar(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public class Question { 4 | 5 | 6 | public static void main(String[] args) { 7 | AnimalQueue animals = new AnimalQueue(); 8 | animals.enqueue(new Cat("Callie")); 9 | animals.enqueue(new Cat("Kiki")); 10 | animals.enqueue(new Dog("Fido")); 11 | animals.enqueue(new Dog("Dora")); 12 | animals.enqueue(new Cat("Kari")); 13 | animals.enqueue(new Dog("Dexter")); 14 | animals.enqueue(new Dog("Dobo")); 15 | animals.enqueue(new Cat("Copa")); 16 | 17 | System.out.println(animals.dequeueAny().name()); 18 | System.out.println(animals.dequeueAny().name()); 19 | System.out.println(animals.dequeueAny().name()); 20 | 21 | animals.enqueue(new Dog("Dapa")); 22 | animals.enqueue(new Cat("Kilo")); 23 | 24 | while (animals.size() != 0) { 25 | System.out.println(animals.dequeueAny().name()); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_8/ChapQ1.8.py: -------------------------------------------------------------------------------- 1 | #Assume you have a method isSubstring which checks if one word is a 2 | #substring of another. Given two strings, s1 and s2, write code to check if s2 is 3 | #a rotation of s1 using only one call to isSubstring (e.g.,"waterbottle" is a rotation of "erbottlewat"). 4 | 5 | def isSubstring(s1,s2): 6 | return s1.find(s2) > -1 7 | 8 | def rotatedStringHasSubstring(s1,s2): 9 | #doubling the string ensures a complete substring regardless of rotation 10 | if len(s2)!=len(s1): 11 | return False 12 | doubles1 = s1 + s1 13 | return isSubstring(doubles1,s2) 14 | 15 | 16 | 17 | #testing 18 | if rotatedStringHasSubstring("waterbottle","erbottlewat"): 19 | print "Test 1 Passed" 20 | 21 | if not rotatedStringHasSubstring("waterbottle","nope"): 22 | print "Test 2 Passed" 23 | 24 | if not rotatedStringHasSubstring("waterbottlewater","waterbottle"): 25 | print "Test 3 Passed" 26 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_2/Server.java: -------------------------------------------------------------------------------- 1 | package Question10_2; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Server { 6 | HashMap machines = new HashMap(); 7 | HashMap personToMachineMap = new HashMap(); 8 | 9 | public Machine getMachineWithId(int machineID) { 10 | return machines.get(machineID); 11 | } 12 | 13 | public int getMachineIDForUser(int personID) { 14 | Integer machineID = personToMachineMap.get(personID); 15 | return machineID == null ? -1 : machineID; 16 | } 17 | 18 | public Person getPersonWithID(int personID) { 19 | Integer machineID = personToMachineMap.get(personID); 20 | if (machineID == null) { 21 | return null; 22 | } 23 | Machine machine = getMachineWithId(machineID); 24 | if (machine == null) { 25 | return null; 26 | } 27 | return machine.getPersonWithID(personID); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /python/Chapter 3/Question3_5/ChapQ3.5.py: -------------------------------------------------------------------------------- 1 | class MyQueue(object): 2 | def __init__(self): 3 | self.s = [[], []] 4 | def push(self, value): 5 | self.s[0].append(value) 6 | def pop(self): 7 | if len(self.s[1]) > 0: 8 | return self.s[1].pop() 9 | while len(self.s[0]) > 0: 10 | self.s[1].append(self.s[0].pop()) 11 | if len(self.s[1]) == 0: 12 | return None 13 | return self.s[1].pop() 14 | 15 | def length(self): 16 | return len(self.s[0]) + len(self.s[1]) 17 | 18 | def empty(self): 19 | return self.length() == 0 20 | 21 | q1 = MyQueue() 22 | from Queue import Queue 23 | q2 = Queue() 24 | 25 | #testing 26 | from random import randrange 27 | for step in xrange(20): 28 | operation = randrange(10) 29 | if operation < 7: 30 | q1.push(operation) 31 | q2.put(operation) 32 | print "push", operation 33 | elif not q2.empty(): 34 | print "pop", q1.pop(), q2.get() 35 | while not q2.empty(): 36 | print "pop", q1.pop(), q2.get() -------------------------------------------------------------------------------- /dart/Chapter18/Question18_3/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | /* Random number between lower and higher, inclusive */ 6 | int rand(int lower, int higher) { 7 | return lower + (random.nextDouble() * (higher - lower + 1)).toInt(); 8 | } 9 | 10 | /* 11 | * pick M elements from original array. Clone original array so that 12 | * we don't destory the input. 13 | */ 14 | List pickMRandomly(List original, int m) { 15 | List subset = new List(m); 16 | List array = new List.from(original); 17 | 18 | for (int j = 0; j < m; j++) { 19 | int index = rand(j, array.length - 1); 20 | subset[j] = array[index]; 21 | array[index] = array[j]; // array[j] is now "Dead" 22 | } 23 | 24 | return subset; 25 | } 26 | 27 | void main() { 28 | List cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; 29 | print(cards); 30 | List s = pickMRandomly(cards, 4); 31 | print(s); 32 | } 33 | -------------------------------------------------------------------------------- /dart/Chapter11/Question11_6/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/assorted_methods.dart'; 2 | bool findElement(List> matrix, int elem) { 3 | int row = 0; 4 | int col = matrix[0].length - 1; 5 | while (row < matrix.length && col >= 0) { 6 | if (matrix[row][col] == elem) { 7 | return true; 8 | } else if (matrix[row][col] > elem) { 9 | col--; 10 | } else { 11 | row++; 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | 18 | void main() { 19 | 20 | int M = 10; 21 | int N = 5; 22 | List> matrix = new List>(M); 23 | for (int i = 0; i < M; i++) { 24 | matrix[i] = new List(N); 25 | for (int j = 0; j < N; j++) { 26 | matrix[i][j] = 10 * i + j; 27 | } 28 | } 29 | 30 | printIntMatrix(matrix); 31 | 32 | for (int i = 0; i < M; i++) { 33 | for (int j = 0; j < M; j++) { 34 | int v = 10 * i + j; 35 | print("$v: ${findElement(matrix, v)}"); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /java/Chapter 5/Question5_5/Question.java: -------------------------------------------------------------------------------- 1 | package Question5_5; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | public static int bitSwapRequired(int a, int b) { 7 | int count = 0; 8 | for (int c = a ^ b; c != 0; c = c >> 1) { 9 | count += c & 1; 10 | } 11 | return count; 12 | } 13 | 14 | public static int bitSwapRequired2(int a, int b){ 15 | int count = 0; 16 | for (int c = a ^ b; c != 0; c = c & (c-1)) { 17 | count++; 18 | } 19 | return count; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int a = 23432; 24 | int b = 512132; 25 | System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a)); 26 | System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b)); 27 | int nbits = bitSwapRequired(a, b); 28 | int nbits2 = bitSwapRequired2(a, b); 29 | System.out.println("Required number of bits: " + nbits + " " + nbits2); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_7/tozeros.py: -------------------------------------------------------------------------------- 1 | def showAsMatrix(mat): 2 | [print(i) for i in mat] 3 | 4 | def tozeros(seq): 5 | PATTERN = 0 6 | 7 | rowlen = range(len(seq)) 8 | colen = range(len(seq[0])) 9 | 10 | rowReset = [False for _ in rowlen] 11 | colReset = [False for _ in colen] 12 | 13 | # first pass, mark the pattern 14 | for r in rowlen: 15 | for c in colen: 16 | if seq[r][c] == PATTERN: 17 | rowReset[r] = colReset[c] = True 18 | 19 | # second pass, modify the sequence in place 20 | for r in rowlen: 21 | for c in colen: 22 | if rowReset[r] or colReset[c]: 23 | seq[r][c] = 0 24 | 25 | return seq 26 | 27 | 28 | if __name__ == '__main__': 29 | matrix = [ [18, 0, 27, -5], 30 | [4, -7, 12, 1], 31 | [28, 1, 9, 0] ] 32 | 33 | showAsMatrix(matrix) 34 | tozeros(matrix) 35 | print() 36 | showAsMatrix(matrix) 37 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionLocks/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionLocks; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | NoLockATM noLockATM = new NoLockATM(); 7 | LockedATM lockedATM = new LockedATM(); 8 | MyClass thread1 = new MyClass(noLockATM, lockedATM); 9 | MyClass thread2 = new MyClass(noLockATM, lockedATM); 10 | 11 | thread1.start(); 12 | thread2.start(); 13 | 14 | try { 15 | Thread.sleep(1000); 16 | } catch (InterruptedException e) { 17 | // TODO Auto-generated catch block 18 | e.printStackTrace(); 19 | } 20 | thread1.waitUntilDone(); 21 | thread2.waitUntilDone(); 22 | 23 | System.out.println("NoLock ATM: " + noLockATM.getBalance()); 24 | System.out.println("Locked ATM: " + lockedATM.getBalance()); 25 | int v = thread1.delta + thread2.delta + 100; 26 | System.out.println("Should Be: " + v); 27 | System.out.println("Program terminating."); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /python/Chapter 3/Question3_4/Q3_4.py: -------------------------------------------------------------------------------- 1 | class Hanoi: 2 | 3 | def __init__(self, size): 4 | self.towers = [[], [], []] 5 | self.size = size 6 | self.towers[0] = [x for x in range(size, 0, -1)] 7 | 8 | def playHanoi(self): 9 | self.printTowers() 10 | self.moveDisk(self.size, 1, 2, 3) 11 | self.printTowers() 12 | 13 | def moveDisk(self, size, fr, helper, to): 14 | if size == 1: 15 | data = self.towers[fr-1].pop() 16 | self.towers[to-1].append(data) 17 | print "Disk", data, ": Tower", fr, "->", to 18 | else: 19 | self.moveDisk(size - 1, fr, to, helper) 20 | self.moveDisk(1, fr, helper, to) 21 | self.moveDisk(size - 1, helper, fr, to) 22 | 23 | def printTowers(self): 24 | for i in self.towers: 25 | print i 26 | 27 | 28 | 29 | 30 | #----------------test--------------- 31 | hanoi = Hanoi(4) 32 | hanoi.playHanoi() 33 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_8/Question1_8.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "Question1_8.h" 4 | 5 | using namespace std; 6 | 7 | bool Question1_8::isRotation(const string& s1, const string& s2){ 8 | int len = s1.length(); 9 | if(len == s2.length() && len > 0) { 10 | string s1s1 = s1+s1; 11 | return s1s1.find(s2) != string::npos; 12 | } 13 | return false; 14 | } 15 | 16 | string Question1_8::result(bool value) { 17 | if(value) { 18 | return "True"; 19 | } 20 | return "False"; 21 | } 22 | 23 | int Question1_8::run() { 24 | string a = "apple"; 25 | string b = "leapp"; 26 | cout << "Checking if string: " << a << " is a rotation of string: " << b << ": " 27 | << result(isRotation(a, b)) << endl; 28 | 29 | a = "james"; 30 | b = "mesje"; 31 | cout << "Checking if string: " << a << " is a rotation of string: " << b << ": " 32 | << result(isRotation(a, b)) << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /c++/Chapter 1/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Question1_1/Question1_1.h" 2 | #include "Question1_2/Question1_2.h" 3 | #include "Question1_3/Question1_3.h" 4 | #include "Question1_3/Question1_3_B.h" 5 | #include "Question1_4/Question1_4.h" 6 | #include "Question1_5/Question1_5.h" 7 | #include "Question1_6/Question1_6.h" 8 | #include "Question1_7/Question1_7.h" 9 | #include "Question1_8/Question1_8.h" 10 | #include "Misc/SimpleHashTable.h" 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | /** 17 | * Main for running exercises from Chapter 1 18 | */ 19 | int main() { 20 | Question1_8().run(); 21 | 22 | //SimpleHashTable map(5); 23 | //map.insert(10, true); 24 | //cout << map.get(10) << endl; 25 | //map.printTable(); 26 | //map.remove(10); 27 | //try { 28 | // map.get(10); 29 | //} catch(const out_of_range&) { 30 | // cout << "Attempted to remove a non existing key from the hash table." << endl; 31 | //} 32 | 33 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Vehicle.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | import java.util.ArrayList; 4 | 5 | public abstract class Vehicle { 6 | protected ArrayList parkingSpots = new ArrayList(); 7 | protected String licensePlate; 8 | protected int spotsNeeded; 9 | protected VehicleSize size; 10 | 11 | public int getSpotsNeeded() { 12 | return spotsNeeded; 13 | } 14 | 15 | public VehicleSize getSize() { 16 | return size; 17 | } 18 | 19 | /* Park vehicle in this spot (among others, potentially) */ 20 | public void parkInSpot(ParkingSpot spot) { 21 | parkingSpots.add(spot); 22 | } 23 | 24 | /* Remove car from spot, and notify spot that it's gone */ 25 | public void clearSpots() { 26 | for (int i = 0; i < parkingSpots.size(); i++) { 27 | parkingSpots.get(i).removeVehicle(); 28 | } 29 | parkingSpots.clear(); 30 | } 31 | 32 | public abstract boolean canFitInSpot(ParkingSpot spot); 33 | public abstract void print(); 34 | } 35 | -------------------------------------------------------------------------------- /dart/Chapter11/Question11_2/questionB.dart: -------------------------------------------------------------------------------- 1 | 2 | String sortChars(String s) { 3 | List content = s.split(''); 4 | content.sort(); 5 | return content.join(); 6 | } 7 | 8 | void sort(List array) { 9 | Map> hash = new Map>(); 10 | 11 | /* Group words by anagram */ 12 | for (String s in array) { 13 | String key = sortChars(s); 14 | if (!hash.containsKey(key)) { 15 | hash[key] = new List(); 16 | } 17 | List anagrams = hash[key]; 18 | anagrams.add(s); 19 | } 20 | 21 | /* Convert hash table to array */ 22 | int index = 0; 23 | for (String key in hash.keys) { 24 | List list = hash[key]; 25 | for (String t in list) { 26 | array[index] = t; 27 | index++; 28 | } 29 | } 30 | } 31 | 32 | void main() { 33 | List array = ["apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee"]; 34 | print(array); 35 | sort(array); 36 | print(array); 37 | } -------------------------------------------------------------------------------- /java/Chapter 4/Question4_5/Question.java: -------------------------------------------------------------------------------- 1 | package Question4_5; 2 | 3 | import CtCILibrary.TreeNode; 4 | 5 | public class Question { 6 | public static Integer last_printed = null; 7 | public static boolean checkBST(TreeNode n) { 8 | if (n == null) { 9 | return true; 10 | } 11 | 12 | // Check / recurse left 13 | if (!checkBST(n.left)) { 14 | return false; 15 | } 16 | 17 | // Check current 18 | if (last_printed != null && n.data <= last_printed) { 19 | return false; 20 | } 21 | last_printed = n.data; 22 | 23 | // Check / recurse right 24 | if (!checkBST(n.right)) { 25 | return false; 26 | } 27 | return true; 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] array = {Integer.MIN_VALUE, Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1, Integer.MAX_VALUE}; 32 | TreeNode node = TreeNode.createMinimalBST(array); 33 | //node.left.data = 5; 34 | //node.left.right.data = 3; 35 | System.out.println(checkBST(node)); 36 | } 37 | } -------------------------------------------------------------------------------- /python/Chapter 1/Question1_6/rotateimg.py: -------------------------------------------------------------------------------- 1 | def showAsMatrix(mat): 2 | [print(i) for i in mat] 3 | 4 | def rotate(seq): 5 | orig = list(seq) # keep a copy of the original sequence 6 | STEP = END = -1 # access elements N..0 one-by-one 7 | r = range(len(seq[0])-1, END, STEP) # the length is fixed, calculate it only once 8 | for idx, _ in enumerate(seq): 9 | # list 0 consists of elements list[N][0], list[N-1][0], ..., list[0][0] 10 | # list 1 consists of elements list[N][1], list[N-1][1], ..., list[0][1], etc. 11 | seq[idx] = [orig[n][idx] for n in r] 12 | return seq 13 | 14 | if __name__ == '__main__': 15 | x = [ ['p00', 'p01', 'p02', 'p03'], 16 | ['p10', 'p11', 'p12', 'p13'], 17 | ['p20', 'p21', 'p22', 'p23'], 18 | ['p30', 'p31', 'p32', 'p33'] ] 19 | 20 | print('original matrix') 21 | showAsMatrix(x) 22 | y = rotate(x) 23 | print() 24 | print('matrix rotated 90 degrees right') 25 | showAsMatrix(y) 26 | -------------------------------------------------------------------------------- /dart/Chapter9/Introduction/fibonacci_fb.dart: -------------------------------------------------------------------------------- 1 | 2 | int max = 100; 3 | List fib = new List(max); 4 | int fibonacci(int i) { 5 | if (i == 0) { 6 | return 0; 7 | } 8 | 9 | if (i == 1) { 10 | return 1; 11 | } 12 | 13 | if (fib[i] != null) { 14 | return fib[i]; 15 | } 16 | 17 | fib[i] = fibonacci(i - 1) + fibonacci(i - 2); 18 | return fib[i]; 19 | } 20 | 21 | void main() { 22 | 23 | int trials = 10; // Run code multiple times to compute average time. 24 | List times = new List(max); 25 | for (int i = 0; i < times.length; i++) { 26 | times[i]=0; 27 | } 28 | Stopwatch sw = new Stopwatch(); 29 | 30 | for (int j = 0; j < trials; j++) { // Run this 10 times to compute 31 | for (int i = 0; i < max; i++) { 32 | fib = new List(max); 33 | sw.start(); 34 | fibonacci(i); 35 | sw.stop(); 36 | times[i] += sw.elapsedMilliseconds; 37 | } 38 | } 39 | 40 | for (int j = 0; j < max; j++) { 41 | print("$j: ${times[j]/trials}ms"); 42 | } 43 | } -------------------------------------------------------------------------------- /python/Chapter 2/kthlast.py: -------------------------------------------------------------------------------- 1 | from classes.linkedlist import * 2 | 3 | def kthToLast(ml, k): 4 | '''kth to last element using indexing''' 5 | if len(ml) == 0 or k > len(ml) or k < 1: 6 | return None 7 | 8 | kth = len(ml) - k 9 | if kth < 1: 10 | return None 11 | 12 | n = ml.head 13 | for _ in range(kth): 14 | n = n.next 15 | return n 16 | 17 | def kthToLastRunner(ml, k): 18 | if len(ml) == 0 or k >= len(ml) or k < 1: 19 | return None 20 | 21 | # go to node k 22 | kth = ml.head 23 | for _ in range(k): 24 | kth = kth.next 25 | 26 | # when node k reaches the end node n 27 | # is the kth to last node 28 | n = ml.head 29 | while kth: 30 | n, kth = n.next, kth.next 31 | return n 32 | 33 | if __name__ == '__main__': 34 | ml = LinkedList(0) 35 | [ml.append(i) for i in (3, -5, 2, 40, -7)] 36 | print(ml) 37 | for i in (1, 3): 38 | n = kthToLast(ml, i) 39 | print('kthToLast({}) = {}'.format(i, n)) 40 | -------------------------------------------------------------------------------- /java/Chapter 1/Question1_3/QuestionB.java: -------------------------------------------------------------------------------- 1 | package Question1_3; 2 | 3 | public class QuestionB { 4 | public static boolean permutation(String s, String t) { 5 | if (s.length() != t.length()) { 6 | return false; 7 | } 8 | 9 | int[] letters = new int[256]; 10 | 11 | char[] s_array = s.toCharArray(); 12 | for (char c : s_array) { // count number of each char in s. 13 | letters[c]++; 14 | } 15 | 16 | for (int i = 0; i < t.length(); i++) { 17 | int c = (int) t.charAt(i); 18 | if (--letters[c] < 0) { 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | 26 | public static void main(String[] args) { 27 | String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}}; 28 | for (String[] pair : pairs) { 29 | String word1 = pair[0]; 30 | String word2 = pair[1]; 31 | boolean anagram = permutation(word1, word2); 32 | System.out.println(word1 + ", " + word2 + ": " + anagram); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /c++/ctci.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.21005.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter 1", "Chapter 1\Chapter 1.vcxproj", "{4B79D473-DF1B-4844-90CA-A853705C8465}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Release|Win32 = Release|Win32 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {4B79D473-DF1B-4844-90CA-A853705C8465}.Debug|Win32.ActiveCfg = Debug|Win32 15 | {4B79D473-DF1B-4844-90CA-A853705C8465}.Debug|Win32.Build.0 = Debug|Win32 16 | {4B79D473-DF1B-4844-90CA-A853705C8465}.Release|Win32.ActiveCfg = Release|Win32 17 | {4B79D473-DF1B-4844-90CA-A853705C8465}.Release|Win32.Build.0 = Release|Win32 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /java/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /dart/Chapter9/Question9_5/question.dart: -------------------------------------------------------------------------------- 1 | 2 | List getPerms(String str) { 3 | if (str == null) { 4 | return null; 5 | } 6 | 7 | List permutations = new List(); 8 | if (str.length == 0) { // base case 9 | permutations.add(""); 10 | return permutations; 11 | } 12 | 13 | String first = str[0]; // get the first character 14 | String remainder = str.substring(1); 15 | List words = getPerms(remainder); 16 | for (String word in words) { 17 | for (int j = 0; j <= word.length; j++) { 18 | String s = insertCharAt(word, first, j); 19 | permutations.add(s); 20 | } 21 | } 22 | return permutations; 23 | } 24 | 25 | String insertCharAt(String word, String c, int i) { 26 | String start = word.substring(0, i); 27 | String end = word.substring(i); 28 | return "${start}${c}${end}"; 29 | } 30 | 31 | void main() { 32 | List list = getPerms("abc"); 33 | print("There are ${list.length} permutations."); 34 | for (String s in list) { 35 | print(s); 36 | } 37 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/Display.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | public class Display { 4 | private Book activeBook; 5 | private User activeUser; 6 | private int pageNumber = 0; 7 | 8 | public void displayUser(User user) { 9 | activeUser = user; 10 | refreshUsername(); 11 | } 12 | 13 | public void displayBook(Book book) { 14 | pageNumber = 0; 15 | activeBook = book; 16 | 17 | refreshTitle(); 18 | refreshDetails(); 19 | refreshPage(); 20 | } 21 | 22 | public void refreshUsername() { 23 | /* updates username display */ 24 | } 25 | 26 | public void refreshTitle() { 27 | /* updates title display */ 28 | } 29 | 30 | public void refreshDetails() { 31 | /* updates details display */ 32 | } 33 | 34 | public void refreshPage() { 35 | /* updated page display */ 36 | } 37 | 38 | public void turnPageForward() { 39 | pageNumber++; 40 | refreshPage(); 41 | } 42 | 43 | public void turnPageBackward() { 44 | pageNumber--; 45 | refreshPage(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionLocks/LockedATM.java: -------------------------------------------------------------------------------- 1 | package IntroductionLocks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class LockedATM { 7 | private Lock lock; 8 | private int balance = 100; 9 | 10 | public LockedATM() { 11 | lock = new ReentrantLock(); 12 | } 13 | 14 | public int withdraw(int value) { 15 | lock.lock(); 16 | int temp = balance; 17 | try { 18 | Thread.sleep(100); 19 | temp = temp - value; 20 | Thread.sleep(100); 21 | balance = temp; 22 | } catch (InterruptedException e) { } 23 | lock.unlock(); 24 | return temp; 25 | } 26 | 27 | public int deposit(int value) { 28 | lock.lock(); 29 | int temp = balance; 30 | try { 31 | Thread.sleep(100); 32 | temp = temp + value; 33 | Thread.sleep(100); 34 | balance = temp; 35 | } catch (InterruptedException e) { } 36 | lock.unlock(); 37 | return temp; 38 | } 39 | 40 | public int getBalance() { 41 | return balance; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_3/Question1_3_B.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Question1_3_B.h" 5 | 6 | using namespace std; 7 | 8 | bool Question1_3_B::permutation(const string& a, const string& b) { 9 | if(a.length() != b.length()) { 10 | return false; 11 | } 12 | 13 | int ascii_set[256] = {0}; 14 | for(int i = 0; i < a.length(); i++) { 15 | int val = (int)a[i]; 16 | ascii_set[val]++; 17 | } 18 | 19 | for(int i = 0; i < b.length(); i++) { 20 | int val = (int)b[i]; 21 | if((--ascii_set[val]) < 0) { 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | 28 | string Question1_3_B::result(bool value) { 29 | if(value) { 30 | return "True"; 31 | } 32 | return "False"; 33 | } 34 | 35 | int Question1_3_B::run() { 36 | string a = "apple"; 37 | string b = "papel"; 38 | cout << "Result for " << a << " and " << b << " is " 39 | << result(permutation(a, b)) << endl; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /dart/Chapter1/Question1_3/question.dart: -------------------------------------------------------------------------------- 1 | /* Given two strings, write a method to decide 2 | * if one is a permutation of the other 3 | */ 4 | 5 | /* Solution by sorting the strings. 6 | * If two strings are anagrams, then we know 7 | * they have the same characters, but in different 8 | * orders. If we put the strings in the same order 9 | * we just need to compare they are the same. 10 | * 11 | * This may not be the most optimal solution. 12 | */ 13 | 14 | String sort(String s) { 15 | var r = s.codeUnits; 16 | r.sort((a, b) => a.compareTo(b)); 17 | return r.toString(); 18 | // return (s.splitChars()..sort((a,b)=>a.compareTo(b))).toString(); 19 | } 20 | bool permutation(String s, String t) { 21 | return sort(s).compareTo(sort(t)) == 0; 22 | } 23 | 24 | void main() { 25 | List pairs = [["apple", "papel"], ["carrot", "tarroc"], ["hello", "llloh"]]; 26 | pairs.forEach((pair) { 27 | var word1 = pair[0]; 28 | var word2 = pair[1]; 29 | bool anagram = permutation(word1, word2); 30 | print("$word1 $word2 : $anagram"); 31 | }); 32 | } -------------------------------------------------------------------------------- /C/Chapter_1/Question1_1/ChapQ1.1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int unique(char * string){ 5 | if(string == NULL) 6 | return 0; 7 | 8 | int i,j; 9 | int length; 10 | 11 | for(i=0;;i++) 12 | if(string[i] == '\0') 13 | break; 14 | length = i - 1; 15 | 16 | for(i=0;i= 0) { 10 | if (matrix[row][col] == elem) { 11 | return true; 12 | } else if (matrix[row][col] > elem) { 13 | col--; 14 | } else { 15 | row++; 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | public static void main(String[] args) { 22 | int M = 10; 23 | int N = 5; 24 | int[][] matrix = new int[M][N]; 25 | for (int i = 0; i < M; i++) { 26 | for (int j = 0; j < N; j++) { 27 | matrix[i][j] = 10 * i + j; 28 | } 29 | } 30 | 31 | AssortedMethods.printMatrix(matrix); 32 | 33 | for (int i = 0; i < M; i++) { 34 | for (int j = 0; j < M; j++) { 35 | int v = 10 * i + j; 36 | System.out.println(v + ": " + findElement(matrix, v)); 37 | } 38 | } 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_7/Question.java: -------------------------------------------------------------------------------- 1 | package Question10_7; 2 | 3 | public class Question { 4 | 5 | public static String[] generateResults(int i) { 6 | String[] results = {"resultA" + i, "resultB" + i, "resultC" + i}; 7 | return results; 8 | } 9 | 10 | public static void main(String[] args) { 11 | Cache cache = new Cache(); 12 | for (int i = 0; i < 20; i++) { 13 | String query = "query" + i; 14 | cache.insertResults(query, generateResults(i)); 15 | if (i == 9 || i == 16 || i == 19) { 16 | cache.getResults("query" + 2); 17 | cache.getResults("query" + 6); 18 | cache.getResults("query" + 9); 19 | } 20 | } 21 | 22 | for (int i = 0; i < 30; i++) { 23 | String query = "query" + i; 24 | String[] results = cache.getResults(query); 25 | System.out.print(query + ": "); 26 | if (results == null) { 27 | System.out.print("null"); 28 | } else { 29 | for (String s : results) { 30 | System.out.print(s + ", "); 31 | } 32 | } 33 | System.out.println(""); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_11/questionB.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | int rand7() { 6 | while(true) { 7 | int r1 = 2 * rand5(); /* evens between 0 and 9 */ 8 | int r2 = rand5(); /* will be later used to generate a 0 or 1 */ 9 | if (r2 != 4) { /* r2 has an extra even number, so discard the extra */ 10 | int rand1 = r2 % 2; /* Generate 0 or 1 */ 11 | int n = r1 + rand1; /* will be in the range 0 through 9 */ 12 | if (n < 7) { 13 | return n; 14 | } 15 | } 16 | } 17 | } 18 | 19 | int rand5() { 20 | return ((random.nextDouble() * 100) % 5).toInt(); 21 | } 22 | 23 | void main() { 24 | /* 25 | * Test: call rand7 many times and inspect the results; 26 | */ 27 | List arr = new List.fixedLength(7, fill: 0); 28 | 29 | int test_size = 1000000; 30 | for (int k = 0; k < test_size; k++) { 31 | arr[rand7()]++; 32 | } 33 | 34 | for (int i = 0; i < 7; i++) { 35 | double percent = 100.0 * arr[i] / test_size; 36 | print ("$i appeared $percent% of the time."); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java/Chapter 1/Question1_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question1_8; 2 | 3 | public class Question { 4 | public static boolean isSubstring(String big, String small) { 5 | if (big.indexOf(small) >= 0) { 6 | return true; 7 | } else { 8 | return false; 9 | } 10 | } 11 | 12 | public static boolean isRotation(String s1, String s2) { 13 | int len = s1.length(); 14 | /* check that s1 and s2 are equal length and not empty */ 15 | if (len == s2.length() && len > 0) { 16 | /* concatenate s1 and s1 within new buffer */ 17 | String s1s1 = s1 + s1; 18 | return isSubstring(s1s1, s2); 19 | } 20 | return false; 21 | } 22 | 23 | public static void main(String[] args) { 24 | String[][] pairs = {{"apple", "pleap"}, {"waterbottle", "erbottlewat"}, {"camera", "macera"}}; 25 | for (String[] pair : pairs) { 26 | String word1 = pair[0]; 27 | String word2 = pair[1]; 28 | boolean is_rotation = isRotation(word1, word2); 29 | System.out.println(word1 + ", " + word2 + ": " + is_rotation); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_8/RankNode.java: -------------------------------------------------------------------------------- 1 | package Question11_8; 2 | 3 | public class RankNode { 4 | public int left_size = 0; 5 | public RankNode left; 6 | public RankNode right; 7 | public int data = 0; 8 | public RankNode(int d) { 9 | data = d; 10 | } 11 | 12 | public void insert(int d) { 13 | if (d <= data) { 14 | if (left != null) { 15 | left.insert(d); 16 | } else { 17 | left = new RankNode(d); 18 | } 19 | left_size++; 20 | } else { 21 | if (right != null) { 22 | right.insert(d); 23 | } else { 24 | right = new RankNode(d); 25 | } 26 | } 27 | } 28 | 29 | public int getRank(int d) { 30 | if (d == data) { 31 | return left_size; 32 | } else if (d < data) { 33 | if (left == null) { 34 | return -1; 35 | } else { 36 | return left.getRank(d); 37 | } 38 | } else { 39 | int right_rank = right == null ? -1 : right.getRank(d); 40 | if (right_rank == -1) { 41 | return -1; 42 | } else { 43 | return left_size + 1 + right_rank; 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_5/MyQueue.java: -------------------------------------------------------------------------------- 1 | package Question3_5; 2 | 3 | import java.util.Stack; 4 | 5 | public class MyQueue { 6 | Stack stackNewest, stackOldest; 7 | 8 | public MyQueue() { 9 | stackNewest = new Stack(); 10 | stackOldest = new Stack(); 11 | } 12 | 13 | public int size() { 14 | return stackNewest.size() + stackOldest.size(); 15 | } 16 | 17 | public void add(T value) { 18 | // Push onto stack1 19 | stackNewest.push(value); 20 | } 21 | 22 | /* Move elements from stackNewest into stackOldest. This is usually done so that we can 23 | * do operations on stackOldest. 24 | */ 25 | private void shiftStacks() { 26 | if (stackOldest.isEmpty()) { 27 | while (!stackNewest.isEmpty()) { 28 | stackOldest.push(stackNewest.pop()); 29 | } 30 | } 31 | } 32 | 33 | public T peek() { 34 | shiftStacks(); 35 | return stackOldest.peek(); // retrieve the oldest item. 36 | } 37 | 38 | public T remove() { 39 | shiftStacks(); 40 | return stackOldest.pop(); // pop the oldest item. 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/OnlineReaderSystem.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | public class OnlineReaderSystem { 4 | private Library library; 5 | private UserManager userManager; 6 | private Display display; 7 | 8 | private Book activeBook; 9 | private User activeUser; 10 | 11 | public OnlineReaderSystem() { 12 | userManager = new UserManager(); 13 | library = new Library(); 14 | display = new Display(); 15 | } 16 | 17 | public Library getLibrary() { 18 | return library; 19 | } 20 | 21 | public UserManager getUserManager() { 22 | return userManager; 23 | } 24 | 25 | public Display getDisplay() { 26 | return display; 27 | } 28 | 29 | public Book getActiveBook() { 30 | return activeBook; 31 | } 32 | 33 | public void setActiveBook(Book book) { 34 | display.displayBook(book); 35 | activeBook = book; 36 | } 37 | 38 | public User getActiveUser() { 39 | return activeUser; 40 | } 41 | 42 | public void setActiveUser(User user) { 43 | activeUser = user; 44 | display.displayUser(user); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /java/Chapter 1/Question1_1/Question.java: -------------------------------------------------------------------------------- 1 | package Question1_1; 2 | 3 | public class Question { 4 | 5 | public static boolean isUniqueChars(String str) { 6 | if (str.length() > 256) { 7 | return false; 8 | } 9 | int checker = 0; 10 | for (int i = 0; i < str.length(); i++) { 11 | int val = str.charAt(i) - 'a'; 12 | if ((checker & (1 << val)) > 0) return false; 13 | checker |= (1 << val); 14 | } 15 | return true; 16 | } 17 | 18 | public static boolean isUniqueChars2(String str) { 19 | if (str.length() > 256) { 20 | return false; 21 | } 22 | boolean[] char_set = new boolean[256]; 23 | for (int i = 0; i < str.length(); i++) { 24 | int val = str.charAt(i); 25 | if (char_set[val]) return false; 26 | char_set[val] = true; 27 | } 28 | return true; 29 | } 30 | 31 | public static void main(String[] args) { 32 | String[] words = {"abcde", "hello", "apple", "kite", "padle"}; 33 | for (String word : words) { 34 | System.out.println(word + ": " + isUniqueChars(word) + " " + isUniqueChars2(word)); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /java/Chapter 9/Introduction/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Fibonacci { 4 | public static int fibonacci(int i) { 5 | if (i == 0) { 6 | return 0; 7 | } 8 | if (i == 1) { 9 | return 1; 10 | } 11 | return fibonacci(i - 1) + fibonacci(i - 2); 12 | } 13 | 14 | /** 15 | * @param args 16 | */ 17 | public static void main(String[] args) { 18 | int max = 35; // WARNING: If you make this above 40ish, your computer may serious slow down. 19 | int trials = 10; // Run code multiple times to compute average time. 20 | double[] times = new double[max]; // Store times 21 | 22 | 23 | for (int j = 0; j < trials; j++) { // Run this 10 times to compute 24 | for (int i = 0; i < max; i++) { 25 | long start = System.currentTimeMillis(); 26 | fibonacci(i); 27 | long end = System.currentTimeMillis(); 28 | long time = end - start; 29 | times[i] += time; 30 | } 31 | } 32 | 33 | for (int j = 0; j < max; j++) { 34 | System.out.println(j + ": " + times[j] / trials + "ms"); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_3/Question1_3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Question1_3.h" 5 | 6 | using namespace std; 7 | 8 | bool Question1_3::permutation(const string& a, const string& b) { 9 | // Create a copy of the two strings, we do not wish to modify those that were passed as parameters. 10 | string str_a(a); 11 | string str_b(b); 12 | 13 | if(str_a.length() != str_b.length()) { 14 | return false; 15 | } 16 | 17 | sort(str_a.begin(), str_a.end()); 18 | sort(str_b.begin(), str_b.end()); 19 | for(int i = 0; i < str_a.length(); i++) { 20 | if(str_a[i] != str_b[i]) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | string Question1_3::result(bool value) { 28 | if(value) { 29 | return "True"; 30 | } 31 | return "False"; 32 | } 33 | 34 | int Question1_3::run() { 35 | string a = "apple"; 36 | string b = "papel"; 37 | cout << "Result for " << a << " and " << b << " is " 38 | << result(permutation(a, b)) << endl; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /python/Chapter 2/removeduplicates.py: -------------------------------------------------------------------------------- 1 | from classes.linkedlist import * 2 | 3 | def removeDupl(ml): 4 | '''Remove duplicates using a temporary buffer''' 5 | found = set() 6 | n = ml.head 7 | prev = None 8 | while n: 9 | # if the current node already exists "remove" it 10 | if n.data in found: 11 | assert prev, 'prev should not be None' 12 | prev.next = n.next 13 | # remember the visited nodes 14 | else: 15 | found.add(n.data) 16 | prev = n 17 | n = n.next 18 | 19 | def removeDuplNoBuf(ml): 20 | '''Remove duplicates without a temporary buffer''' 21 | n = ml.head 22 | while n: 23 | r = n # the runner node 24 | while r.next: 25 | if r.next == n: 26 | r.next = r.next.next 27 | else: 28 | r = r.next 29 | n = n.next 30 | 31 | if __name__ == '__main__': 32 | ml = LinkedList(0) 33 | [ml.append(i) for i in (0, 3, 4, 0, 3, 18, 9, 18, 7, 4, 12)] 34 | print(ml) 35 | removeDupl(ml) 36 | print(ml) 37 | -------------------------------------------------------------------------------- /java/Chapter 1/Question1_6/Question.java: -------------------------------------------------------------------------------- 1 | package Question1_6; 2 | 3 | import CtCILibrary.*; 4 | 5 | public class Question { 6 | 7 | public static void rotate(int[][] matrix, int n) { 8 | for (int layer = 0; layer < n / 2; ++layer) { 9 | int first = layer; 10 | int last = n - 1 - layer; 11 | for(int i = first; i < last; ++i) { 12 | int offset = i - first; 13 | int top = matrix[first][i]; // save top 14 | 15 | // left -> top 16 | matrix[first][i] = matrix[last-offset][first]; 17 | 18 | // bottom -> left 19 | matrix[last-offset][first] = matrix[last][last - offset]; 20 | 21 | // right -> bottom 22 | matrix[last][last - offset] = matrix[i][last]; 23 | 24 | // top -> right 25 | matrix[i][last] = top; // right <- saved top 26 | } 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[][] matrix = AssortedMethods.randomMatrix(10, 10, 0, 9); 32 | AssortedMethods.printMatrix(matrix); 33 | rotate(matrix, 10); 34 | System.out.println(); 35 | AssortedMethods.printMatrix(matrix); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /dart/utils/linked_list_node.dart: -------------------------------------------------------------------------------- 1 | library linked_list_node; 2 | 3 | class LinkedListNode { 4 | LinkedListNode next; 5 | LinkedListNode prev; 6 | LinkedListNode last; 7 | int data; 8 | LinkedListNode(int d, LinkedListNode n, LinkedListNode p) { 9 | data = d; 10 | setNext(n); 11 | setPrevious(p); 12 | } 13 | 14 | void setNext(LinkedListNode n) { 15 | next = n; 16 | if (this == last) { 17 | last = n; 18 | } 19 | if (n != null && n.prev != this) { 20 | n.setPrevious(this); 21 | } 22 | } 23 | 24 | void setPrevious(LinkedListNode p) { 25 | prev = p; 26 | if (p != null && p.next != this) { 27 | p.setNext(this); 28 | } 29 | } 30 | 31 | String printFoward() { 32 | if (next != null) { 33 | return "$data->${next.printFoward()}"; 34 | } else { 35 | return data.toString(); 36 | } 37 | } 38 | 39 | LinkedListNode clone() { 40 | LinkedListNode next2 = null; 41 | if (next != null) { 42 | next2 = next.clone(); 43 | } 44 | LinkedListNode head2 = new LinkedListNode(data, next2, null); 45 | return head2; 46 | } 47 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_9/Directory.java: -------------------------------------------------------------------------------- 1 | package Question8_9; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Directory extends Entry { 6 | protected ArrayList contents; 7 | 8 | public Directory(String n, Directory p) { 9 | super(n, p); 10 | contents = new ArrayList(); 11 | } 12 | 13 | protected ArrayList getContents() { 14 | return contents; 15 | } 16 | 17 | public int size() { 18 | int size = 0; 19 | for (Entry e : contents) { 20 | size += e.size(); 21 | } 22 | return size; 23 | } 24 | 25 | public int numberOfFiles() { 26 | int count = 0; 27 | for (Entry e : contents) { 28 | if (e instanceof Directory) { 29 | count++; // Directory counts as a file 30 | Directory d = (Directory) e; 31 | count += d.numberOfFiles(); 32 | } else if (e instanceof File) { 33 | count++; 34 | } 35 | } 36 | return count; 37 | } 38 | 39 | public boolean deleteEntry(Entry entry) { 40 | return contents.remove(entry); 41 | } 42 | 43 | public void addEntry(Entry entry) { 44 | contents.add(entry); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_11/QuestionB.java: -------------------------------------------------------------------------------- 1 | package Question17_11; 2 | 3 | public class QuestionB { 4 | public static int rand7() { 5 | while (true) { 6 | int r1 = 2 * rand5(); /* evens between 0 and 9 */ 7 | int r2 = rand5(); /* will be later used to generate a 0 or 1 */ 8 | if (r2 != 4) { /* r2 has an extra even number, so discard the extra */ 9 | int rand1 = r2 % 2; /* Generate 0 or 1 */ 10 | int num = r1 + rand1; /* will be in the range 0 through 9 */ 11 | if (num < 7) { 12 | return num; 13 | } 14 | } 15 | 16 | } 17 | } 18 | 19 | public static int rand5() { 20 | return (int) (Math.random() * 100) % 5; 21 | } 22 | 23 | public static void main(String[] args) { 24 | /* Test: call rand7 many times and inspect the results. */ 25 | int[] arr = new int[7]; 26 | int test_size = 1000000; 27 | for(int k = 0; k < test_size; k++){ 28 | arr[rand7()]++; 29 | } 30 | 31 | for (int i = 0; i < 7; i++) { 32 | double percent = 100.0 * arr[i] / test_size; 33 | System.out.println(i + " appeared " + percent + "% of the time."); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dart/Chapter9/Question9_6/questionB.dart: -------------------------------------------------------------------------------- 1 | 2 | void addParen(List list, int leftRem, int rightRem, List str, int count) { 3 | if (leftRem < 0 || rightRem < leftRem) { 4 | return; // invalid state 5 | } 6 | 7 | if (leftRem == 0 && rightRem == 0) { /* all out of left and right parentheses */ 8 | String s = str.join(); 9 | list.add(s); 10 | } else { 11 | if (leftRem > 0) { // try a left paren, if there are some available 12 | str[count] = '('; 13 | addParen(list, leftRem - 1, rightRem, str, count + 1); 14 | } 15 | 16 | if (rightRem > leftRem) { // try a right paren, if there's a matching left 17 | str[count] = ')'; 18 | addParen(list, leftRem, rightRem - 1, str, count + 1); 19 | } 20 | } 21 | } 22 | 23 | List generateParens(int count) { 24 | List str = new List(count * 2); 25 | List list = new List(); 26 | addParen(list, count, count, str, 0); 27 | return list; 28 | } 29 | 30 | void main() { 31 | List list = generateParens(3); 32 | for (String s in list) { 33 | print(s); 34 | } 35 | print(list.length); 36 | } -------------------------------------------------------------------------------- /java/Chapter 1/Question1_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question1_4; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | // Assume string has sufficient free space at the end 7 | public static void replaceSpaces(char[] str, int length) { 8 | int spaceCount = 0, index, i = 0; 9 | for (i = 0; i < length; i++) { 10 | if (str[i] == ' ') { 11 | spaceCount++; 12 | } 13 | } 14 | index = length + spaceCount * 2; 15 | str[index] = '\0'; 16 | for (i = length - 1; i >= 0; i--) { 17 | if (str[i] == ' ') { 18 | str[index - 1] = '0'; 19 | str[index - 2] = '2'; 20 | str[index - 3] = '%'; 21 | index = index - 3; 22 | } else { 23 | str[index - 1] = str[i]; 24 | index--; 25 | } 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | String str = "abc d e f"; 31 | char[] arr = new char[str.length() + 3 * 2 + 1]; 32 | for (int i = 0; i < str.length(); i++) { 33 | arr[i] = str.charAt(i); 34 | } 35 | replaceSpaces(arr, str.length()); 36 | System.out.println("\"" + AssortedMethods.charArrayToString(arr) + "\""); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_10/Question.java: -------------------------------------------------------------------------------- 1 | package Question8_10; 2 | 3 | public class Question { 4 | 5 | public static void main(String[] args) { 6 | Dummy bob = new Dummy("Bob", 20); 7 | Dummy jim = new Dummy("Jim", 25); 8 | Dummy alex = new Dummy("Alex", 30); 9 | Dummy tim = new Dummy("Tim", 35); 10 | Dummy maxwell = new Dummy("Maxwell", 40); 11 | Dummy john = new Dummy("John", 45); 12 | Dummy julie = new Dummy("Julie", 50); 13 | Dummy christy = new Dummy("Christy", 55); 14 | Dummy tim2 = new Dummy("Tim", 100); // This should replace the first "tim" 15 | 16 | Dummy[] dummies = {bob, jim, alex, tim, maxwell, john, julie, christy, tim2}; 17 | 18 | /* Test: Insert Elements. */ 19 | Hash hash = new Hash(); 20 | for (Dummy d : dummies) { 21 | hash.put(d.getName(), d); 22 | } 23 | 24 | hash.debugPrintHash(); 25 | 26 | /* Test: Recall */ 27 | for (Dummy d : dummies) { 28 | String name = d.getName(); 29 | Dummy dummy = hash.get(name); 30 | System.out.println("Dummy named " + name + ": " + dummy.toString()); 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /dart/Chapter5/Question5_1/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int updateBits(int n, int m, int i, int j) { 3 | 4 | // Validation 5 | if (i >= 32 || j < i) { 6 | return 0; 7 | } 8 | 9 | /** 10 | * Create a mask to clear bits i through j in n 11 | * EXAMPLE: i = 2, j = 4. Result should be 11100011. 12 | * (Using 8 bits for this example. This is obviously not actually 8 13 | * bits.) 14 | */ 15 | int allOnes = ~0; // allOnes 16 | 17 | int left = allOnes << (j + 1); // 1s through position j, then 0s. left = 11100000 18 | int right = ((1 << i) - 1); // 1's after position i. right = 00000011 19 | int mask = left | right; // All 1s, except for 0s between i and j. mask = 11100011 20 | 21 | /* Clear i through j, then put m in there */ 22 | int n_cleared = n & mask; // Clear bits j through i. 23 | int m_shifted = m << i; // Move m into correct position. 24 | 25 | /* OR them, and we're done! */ 26 | return n_cleared | m_shifted; 27 | } 28 | 29 | void main() { 30 | int a = 103217; 31 | print(a.toRadixString(2)); 32 | int b = 13; 33 | print(b.toRadixString(2)); 34 | int c = updateBits(a, b, 4, 12); 35 | print(c.toRadixString(2)); 36 | } -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionLocks/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionLocks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | import CtCILibrary.AssortedMethods; 7 | 8 | public class MyClass extends Thread { 9 | private NoLockATM noLockATM; 10 | private LockedATM lockedATM; 11 | public int delta = 0; 12 | 13 | private Lock completionLock; 14 | 15 | public MyClass(NoLockATM atm1, LockedATM atm2) { 16 | noLockATM = atm1; 17 | lockedATM = atm2; 18 | completionLock = new ReentrantLock(); 19 | } 20 | 21 | public void run() { 22 | completionLock.lock(); 23 | int[] operations = AssortedMethods.randomArray(20, -50, 50); 24 | for (int op : operations) { 25 | delta += op; 26 | if (op < 0) { 27 | int val = op * -1; 28 | noLockATM.withdraw(val); 29 | lockedATM.withdraw(val); 30 | } else { 31 | noLockATM.deposit(op); 32 | lockedATM.deposit(op); 33 | } 34 | } 35 | completionLock.unlock(); 36 | } 37 | 38 | public void waitUntilDone() { 39 | completionLock.lock(); 40 | completionLock.unlock(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_7/QuestionA.java: -------------------------------------------------------------------------------- 1 | package Question7_7; 2 | 3 | import java.util.Queue; 4 | import java.util.LinkedList; 5 | 6 | public class QuestionA { 7 | 8 | public static int removeMin(Queue q) { 9 | int min = q.peek(); 10 | for (Integer v : q) { 11 | if (min > v) { 12 | min = v; 13 | } 14 | } 15 | while (q.contains(min)) { 16 | q.remove(min); 17 | } 18 | return min; 19 | } 20 | 21 | public static void addProducts(Queue q, int v) { 22 | q.add(v * 3); 23 | q.add(v * 5); 24 | q.add(v * 7); 25 | } 26 | 27 | public static int getKthMagicNumber(int k) { 28 | if (k < 0) { 29 | return 0; 30 | } 31 | int val = 1; 32 | Queue q = new LinkedList(); 33 | addProducts(q, 1); 34 | for (int i = 0; i < k; i++) { // Start at 1 since we've already done one iteration 35 | val = removeMin(q); 36 | addProducts(q, val); 37 | } 38 | return val; 39 | } 40 | 41 | public static void main(String[] args) { 42 | for (int i = 0; i < 14; i++) { 43 | System.out.println(i + " : " + getKthMagicNumber(i)); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /dart/Chapter1/Question1_6/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an image represented by an NxN matrix, where each pixel in 3 | * the image is 4 bytes, write a method to rotate the image by 4 | * 90 degrees. Can you do this inplace? 5 | */ 6 | import '../../utils/assorted_methods.dart'; 7 | 8 | void rotate(List> matrix, int n) { 9 | for (int layer = 0; layer < n / 2; ++layer) { 10 | int first = layer; 11 | int last = n - 1 - layer; 12 | for (int i = first; i < last; ++i) { 13 | int offset = i - first; 14 | int top = matrix[first][i]; // save top 15 | 16 | // left -> top 17 | matrix[first][i] = matrix[last - offset][first]; 18 | 19 | // bottom -> left 20 | matrix[last - offset][first] = matrix[last][last - offset]; 21 | 22 | // right -> bottom 23 | matrix[last][last - offset] = matrix[i][last]; 24 | 25 | // top -> right 26 | matrix[i][last] = top; // right <- saved top 27 | } 28 | } 29 | } 30 | 31 | void main() { 32 | List> matrix = randomMatrix(10, 10, 0, 9); 33 | printIntMatrix(matrix); 34 | rotate(matrix, 10); 35 | print("\n"); 36 | printIntMatrix(matrix); 37 | } -------------------------------------------------------------------------------- /java/Chapter 3/Question3_3/Stack.java: -------------------------------------------------------------------------------- 1 | package Question3_3; 2 | 3 | public class Stack { 4 | private int capacity; 5 | public Node top; 6 | public Node bottom; 7 | public int size = 0; 8 | 9 | public Stack(int capacity) { 10 | this.capacity = capacity; 11 | } 12 | 13 | public boolean isFull() { 14 | return capacity == size; 15 | } 16 | 17 | public void join(Node above, Node below) { 18 | if (below != null) below.above = above; 19 | if (above != null) above.below = below; 20 | } 21 | 22 | public boolean push(int v) { 23 | if (size >= capacity) return false; 24 | size++; 25 | Node n = new Node(v); 26 | if (size == 1) bottom = n; 27 | join(n, top); 28 | top = n; 29 | return true; 30 | } 31 | 32 | public int pop() { 33 | Node t = top; 34 | top = top.below; 35 | size--; 36 | return t.value; 37 | } 38 | 39 | public boolean isEmpty() { 40 | return size == 0; 41 | } 42 | 43 | public int removeBottom() { 44 | Node b = bottom; 45 | bottom = bottom.above; 46 | if (bottom != null) bottom.below = null; 47 | size--; 48 | return b.value; 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_9/Entry.java: -------------------------------------------------------------------------------- 1 | package Question8_9; 2 | 3 | public abstract class Entry { 4 | protected Directory parent; 5 | protected long created; 6 | protected long lastUpdated; 7 | protected long lastAccessed; 8 | protected String name; 9 | 10 | public Entry(String n, Directory p) { 11 | name = n; 12 | parent = p; 13 | created = System.currentTimeMillis(); 14 | } 15 | 16 | public boolean delete() { 17 | if (parent == null) { 18 | return false; 19 | } 20 | return parent.deleteEntry(this); 21 | } 22 | 23 | public abstract int size(); 24 | 25 | public String getFullPath() { 26 | if (parent == null) { 27 | return name; 28 | } else { 29 | return parent.getFullPath() + "/" + name; 30 | } 31 | } 32 | 33 | public long getCreationTime() { 34 | return created; 35 | } 36 | 37 | public long getLastUpdatedTime() { 38 | return lastUpdated; 39 | } 40 | 41 | public long getLastAccessedTime() { 42 | return lastAccessed; 43 | } 44 | 45 | public void changeName(String n) { 46 | name = n; 47 | } 48 | 49 | public String getName() { 50 | return name; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /python/Chapter 2/Question2_1.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | 4 | # use a hash table, O(n) 5 | def deleteDups(linkedlist): 6 | if (linkedlist.head != None): 7 | currNode = linkedlist.head 8 | dic = {currNode.value: True} 9 | while currNode.next != None: 10 | if currNode.next.value in dic: 11 | currNode.next = currNode.next.next 12 | else: 13 | dic[currNode.next.value] = True 14 | currNode = currNode.next 15 | 16 | 17 | # use no data structure, O(n2) 18 | def deleteDups2(linkedlist): 19 | currNode = linkedlist.head 20 | while currNode != None: 21 | runner = currNode 22 | while runner.next != None: 23 | if runner.next.value == currNode.value: 24 | runner.next = runner.next.next 25 | else: 26 | runner = runner.next 27 | currNode = currNode.next 28 | 29 | 30 | 31 | 32 | #---------------- test -------------------- 33 | L1 = randomLinkedList(9, 3, 7) 34 | print L1 35 | deleteDups(L1) 36 | print L1 37 | print 38 | L2 = randomLinkedList(9, 3, 7) 39 | print L2 40 | deleteDups2(L2) 41 | print L2 42 | -------------------------------------------------------------------------------- /dart/Chapter4/Question4_7/question_c_bad.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/tree_node.dart'; 2 | 3 | TreeNode commonAncestorBad(TreeNode root, TreeNode p, TreeNode q) { 4 | if (root == null) { 5 | return null; 6 | } 7 | 8 | if (root == p && root == q) { 9 | return root; 10 | } 11 | 12 | TreeNode x = commonAncestorBad(root.left, p, q); 13 | if (x != null && x != p && x != q) { // Found common ancestor 14 | return x; 15 | } 16 | 17 | TreeNode y = commonAncestorBad(root.right, p, q); 18 | if (y != null && y != p && y != q) { 19 | return y; 20 | } 21 | 22 | if (x != null && y != null) { 23 | return root; // This is the common ancestor 24 | } else if (root == p || root == q) { 25 | return root; 26 | } else { 27 | return x == null ? y : x; 28 | } 29 | } 30 | void main() { 31 | List array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 32 | TreeNode root = TreeNode.createMinimalBST(array); 33 | TreeNode n3 = root.find(1); 34 | TreeNode n7 = root.find(7); 35 | TreeNode ancestor = commonAncestorBad(root, n3, n7); 36 | if (ancestor != null) { 37 | ancestor.print(); 38 | print(ancestor.data); 39 | } else { 40 | print("null"); 41 | } 42 | } -------------------------------------------------------------------------------- /java/Chapter 17/Question17_10/Element.java: -------------------------------------------------------------------------------- 1 | package Question17_10; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Element { 6 | public ArrayList attributes; 7 | public ArrayList children; 8 | public String name; 9 | public String value; 10 | 11 | public Element(String n) { 12 | name = n; 13 | attributes = new ArrayList(); 14 | children = new ArrayList(); 15 | } 16 | 17 | public Element(String n, String v) { 18 | name = n; 19 | value = v; 20 | attributes = new ArrayList(); 21 | children = new ArrayList(); 22 | } 23 | 24 | public String getNameCode() { 25 | if (name == "family") { 26 | return "1"; 27 | } else if (name == "person") { 28 | return "2"; 29 | } else if (name == "firstName") { 30 | return "3"; 31 | } else if (name == "lastName") { 32 | return "4"; 33 | } else if (name == "state") { 34 | return "5"; 35 | } 36 | return "--"; 37 | } 38 | 39 | public void insert(Attribute attribute) { 40 | attributes.add(attribute); 41 | } 42 | 43 | public void insert(Element child) { 44 | children.add(child); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_6/testrotate.py: -------------------------------------------------------------------------------- 1 | from rotateimg import * 2 | import unittest 3 | 4 | class TestRotate(unittest.TestCase): 5 | def testEmpty(self): 6 | '''rotate must return empty for empty matrices''' 7 | self.assertEqual(rotate([[]]), [[]]) 8 | 9 | def testOneByOne(self): 10 | '''rotate must return the original for 1x1 matrices''' 11 | self.assertEqual(rotate([[1]]), [[1]]) 12 | 13 | def testTwoByTwo(self): 14 | '''rotate must reverse 90 degrees 2x2 matrices''' 15 | orig = [ [1, 2], 16 | [3, 4] ] 17 | 18 | exp = [ [3, 1], 19 | [4, 2] ] 20 | expected = rotate(orig) 21 | self.assertEqual(expected, exp) 22 | 23 | def testThreeByThree(self): 24 | '''rotate must reverse 90 degrees 3x3 matrices''' 25 | orig = [ [1, 2, 3], 26 | [4, 5, 6], 27 | [7, 8, 9] ] 28 | 29 | exp = [ [7, 4, 1], 30 | [8, 5, 2], 31 | [9, 6, 3] ] 32 | expected = rotate(orig) 33 | self.assertEqual(expected, exp) 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | -------------------------------------------------------------------------------- /dart/Chapter9/Question9_6/questionA.dart: -------------------------------------------------------------------------------- 1 | 2 | String insertInside(String str, int leftIndex) { 3 | String left = str.substring(0, leftIndex + 1); 4 | String right = str.substring(leftIndex + 1, str.length); 5 | return "${left}()${right}"; 6 | } 7 | 8 | Set generateParens(int remaining) { 9 | Set set = new Set(); 10 | if (remaining == 0) { 11 | set.add(""); 12 | } else { 13 | Set prev = generateParens(remaining - 1); 14 | for (String str in prev) { 15 | for (int i = 0; i < str.length; i++) { 16 | if (str[i] == '(') { 17 | String s = insertInside(str, i); 18 | /* 19 | * Add s to set if it's not already in there. Note: 20 | * Set automatically checks for duplicates before 21 | * adding, so an explicit check is not necessary. 22 | */ 23 | set.add(s); 24 | } 25 | } 26 | if (!set.contains('()${str}')) { 27 | set.add("()${str}"); 28 | } 29 | } 30 | } 31 | return set; 32 | } 33 | 34 | void main() { 35 | Set list = generateParens(3); 36 | for (String s in list) { 37 | print(s); 38 | } 39 | 40 | print(list.length); 41 | } -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/IntroductionCollections.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.LinkedList; 7 | import java.util.Vector; 8 | 9 | public class IntroductionCollections { 10 | public static void main(String[] args) { 11 | // ArrayList 12 | ArrayList myArr = new ArrayList(); 13 | myArr.add("one"); 14 | myArr.add("two"); 15 | System.out.println(myArr.get(0)); 16 | 17 | // Vector 18 | Vector myVect = new Vector(); 19 | myVect.add("one"); 20 | myVect.add("two"); 21 | System.out.println(myVect.get(0)); 22 | 23 | // Linked List 24 | LinkedList myLinkedList = new LinkedList(); 25 | myLinkedList.add("two"); 26 | myLinkedList.addFirst("one"); 27 | Iterator iter = myLinkedList.iterator(); 28 | while (iter.hasNext()) { 29 | System.out.println(iter.next()); 30 | } 31 | 32 | // Hash Map 33 | HashMap map = new HashMap(); 34 | map.put("one", "uno"); 35 | map.put("two", "dos"); 36 | System.out.println(map.get("one")); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_9/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/assorted_methods.dart'; 2 | 3 | Map setupDictionary(List book) { 4 | Map table = new Map(); 5 | for (String word in book) { 6 | word = word.toLowerCase(); 7 | if (word.trim() != "") { 8 | if (!table.containsKey(word)) { 9 | table[word] = 0; 10 | } 11 | table[word]++; 12 | } 13 | } 14 | 15 | return table; 16 | } 17 | 18 | int getFrequency(Map table, String word) { 19 | if (table == null || word == null) { 20 | return -1; 21 | } 22 | 23 | word = word.toLowerCase(); 24 | if (table.containsKey(word)) { 25 | return table[word]; 26 | } 27 | 28 | return 0; 29 | } 30 | 31 | void main() { 32 | var wordlist = getListOfWords(); 33 | var dictionary = setupDictionary(wordlist); 34 | var words = ["the", "Lara", "and", "outcropping", "career", "it"]; 35 | for (String word in words) { 36 | print("$word: ${getFrequency(dictionary, word)}"); 37 | } 38 | 39 | // print(dictionary.values.where((v)=>v!=1).toList()); 40 | // dictionary.keys 41 | // .where((k) => dictionary[k] != 1) 42 | // .forEach((v)=> print("$v ${dictionary[v]}")); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /dart/Chapter4/Question4_6/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/tree_node.dart'; 2 | 3 | TreeNode inorderSucc(TreeNode n) { 4 | if (n == null) { 5 | return null; 6 | } 7 | 8 | // Found right children -> return left most node of right subtree 9 | if (n.parent == null || n.right != null) { 10 | return leftMostChild(n.right); 11 | } else { 12 | TreeNode q = n; 13 | TreeNode x = q.parent; 14 | // Go up until we're on left instead of right 15 | while (x != null && x.left != q) { 16 | q = x; 17 | x = x.parent; 18 | } 19 | return x; 20 | } 21 | } 22 | 23 | TreeNode leftMostChild(TreeNode n) { 24 | if (n == null) { 25 | return null; 26 | } 27 | 28 | while (n.left != null) { 29 | n = n.left; 30 | } 31 | 32 | return n; 33 | } 34 | 35 | void main() { 36 | List array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 37 | TreeNode root = TreeNode.createMinimalBST(array); 38 | root.print(); 39 | for (int i = 0; i < array.length; i++) { 40 | TreeNode node = root.find(array[i]); 41 | TreeNode next = inorderSucc(node); 42 | if (next != null) { 43 | print("${node.data} -> ${next.data}"); 44 | } else { 45 | print("${node.data} -> null"); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /python/Chapter 1/Question1_3/testanagram.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from anagram import * 3 | 4 | class TestAnagram(unittest.TestCase): 5 | def testEmpty(self): 6 | '''anagram must return true for empty strings''' 7 | self.assertTrue(anagram('', '')) 8 | 9 | def testSingle(self): 10 | '''anagram must return true for single character strings''' 11 | self.assertTrue(anagram('a', 'a')) 12 | 13 | def testDoubleEq(self): 14 | '''anagram must return true for double same-character strings''' 15 | self.assertTrue(anagram('aa', 'aa')) 16 | 17 | def testValid(self): 18 | '''anagram must return true for known anagrams''' 19 | words = ( ('So dark the con of man', 'Madonna of The Rocks'), 20 | (' ba ', ' Ab ') ) 21 | for (x, y) in words: 22 | self.assertTrue(anagram(x, y)) 23 | 24 | def testInvalid(self): 25 | '''anagram must return false for known non-anagrams''' 26 | words = ( ('hello', 'ello'), 27 | (' anne ', ' annea ') ) 28 | for (x, y) in words: 29 | self.assertFalse(anagram(x, y)) 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | 34 | -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/card.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | abstract class Card { 4 | bool _available = true; 5 | 6 | /* 7 | * number or face that's on card - a number 2 through 10, 8 | * or 11 for Jack, 12 for Queen, 13 for King, or 1 for Ace 9 | */ 10 | int faceValue; 11 | Suit _suit; 12 | 13 | Card(this.faceValue, this._suit); 14 | 15 | int value(); 16 | 17 | Suit suit() => _suit; 18 | 19 | /* returns whether or not the card is available to be given out to someone */ 20 | bool isAvailable() => _available; 21 | 22 | markUnavailable() => _available = false; 23 | markAvailable() => _available = true; 24 | 25 | void print_card() { 26 | List faceValues = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; 27 | StringBuffer sb = new StringBuffer(); 28 | sb.write(faceValues[faceValue - 1]); 29 | switch(suit) { 30 | case Suit.Club: 31 | sb.write('c'); 32 | break; 33 | case Suit.Heart: 34 | sb.write('h'); 35 | break; 36 | case Suit.Diamond: 37 | sb.write('d'); 38 | break; 39 | case Suit.Spade: 40 | sb.write('s'); 41 | break; 42 | } 43 | 44 | print(sb.toString()); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /java/CtCILibrary/CtCILibrary/LinkedListNode.java: -------------------------------------------------------------------------------- 1 | package CtCILibrary; 2 | 3 | public class LinkedListNode { 4 | public LinkedListNode next; 5 | public LinkedListNode prev; 6 | public LinkedListNode last; 7 | public int data; 8 | public LinkedListNode(int d, LinkedListNode n, LinkedListNode p) { 9 | data = d; 10 | setNext(n); 11 | setPrevious(p); 12 | } 13 | 14 | public LinkedListNode() { } 15 | 16 | public void setNext(LinkedListNode n) { 17 | next = n; 18 | if (this == last) { 19 | last = n; 20 | } 21 | if (n != null && n.prev != this) { 22 | n.setPrevious(this); 23 | } 24 | } 25 | 26 | public void setPrevious(LinkedListNode p) { 27 | prev = p; 28 | if (p != null && p.next != this) { 29 | p.setNext(this); 30 | } 31 | } 32 | 33 | public String printForward() { 34 | if (next != null) { 35 | return data + "->" + next.printForward(); 36 | } else { 37 | return ((Integer) data).toString(); 38 | } 39 | } 40 | 41 | public LinkedListNode clone() { 42 | LinkedListNode next2 = null; 43 | if (next != null) { 44 | next2 = next.clone(); 45 | } 46 | LinkedListNode head2 = new LinkedListNode(data, next2, null); 47 | return head2; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /dart/Chapter1/Question1_8/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Assume you have a method isSubstring which checks if one word is a 3 | * substring of another. Given two strings, s1 and s2, write code to check 4 | * if s2 is a rotation of s1 using only one call to isSubstring 5 | * (e.g., "waterbottle" is a rotation of "erbottlewat"). 6 | */ 7 | 8 | bool isSubstring(String big, String small) { 9 | if (big.indexOf(small) >= 0) { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } 15 | 16 | bool isRotation(String s1, String s2) { 17 | int len = s1.length; 18 | /* check that s1 and s2 are equal length and not empty */ 19 | if (len == s2.length && len > 0) { 20 | /* concatenate s1 and s1 within new buffer */ 21 | String s1s1 = "$s1$s1"; 22 | return isSubstring(s1s1, s2); 23 | } 24 | 25 | return false; 26 | } 27 | 28 | void main() { 29 | List> pairs = [["apple", "pleap"], 30 | ["waterbottle", "erbottlewat"], 31 | ["camera", "macera"]]; 32 | for (List pair in pairs) { 33 | String word1 = pair[0]; 34 | String word2 = pair[1]; 35 | bool is_rotation = isRotation(word1, word2); 36 | print("$word1, $word2: $is_rotation"); 37 | } 38 | } -------------------------------------------------------------------------------- /java/Chapter 18/Question18_8/SuffixTreeNode.java: -------------------------------------------------------------------------------- 1 | package Question18_8; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | 6 | public class SuffixTreeNode { 7 | HashMap children = new HashMap(); 8 | 9 | char value; 10 | ArrayList indexes = new ArrayList(); 11 | public SuffixTreeNode() { } 12 | 13 | public void insertString(String s, int index) { 14 | indexes.add(index); 15 | if (s != null && s.length() > 0) { 16 | value = s.charAt(0); 17 | SuffixTreeNode child = null; 18 | if (children.containsKey(value)) { 19 | child = children.get(value); 20 | } else { 21 | child = new SuffixTreeNode(); 22 | children.put(value, child); 23 | } 24 | String remainder = s.substring(1); 25 | child.insertString(remainder, index); 26 | } 27 | } 28 | 29 | public ArrayList search(String s) { 30 | if (s == null || s.length() == 0) { 31 | return indexes; 32 | } else { 33 | char first = s.charAt(0); 34 | if (children.containsKey(first)) { 35 | String remainder = s.substring(1); 36 | return children.get(first).search(remainder); 37 | } 38 | } 39 | return null; 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /dart/Chapter4/Question4_1/question_brute.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import '../../utils/assorted_methods.dart'; 4 | import '../../utils/tree_node.dart'; 5 | 6 | int getHeight(TreeNode root) { 7 | if (root == null) { 8 | return 0; 9 | } 10 | 11 | return max(getHeight(root.left), getHeight(root.right)) + 1; 12 | } 13 | 14 | bool isBalanced(TreeNode root) { 15 | if (root == null) { 16 | return true; 17 | } 18 | 19 | int heightDiff = getHeight(root.left) - getHeight(root.right); 20 | if (heightDiff.abs() > 1) { 21 | return false; 22 | } else { 23 | return isBalanced(root.left) && isBalanced(root.right); 24 | } 25 | } 26 | 27 | void main() { 28 | // Create balanced tree 29 | List array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 30 | TreeNode root = TreeNode.createMinimalBST(array); 31 | print("Root? ${root.data}"); 32 | print("Is balanced? ${isBalanced(root)}"); 33 | root.print(); 34 | 35 | // Could be balanced, actually, but it's very unlikely... 36 | TreeNode unbalanced = new TreeNode(10); 37 | for (int i = 0; i < 10; i++) { 38 | unbalanced.insertInOrder(randomIntInRange(0, 100)); 39 | } 40 | 41 | print("Root? ${unbalanced.data}"); 42 | print("Is balanced? ${isBalanced(unbalanced)}"); 43 | unbalanced.print(); 44 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_9/Question.java: -------------------------------------------------------------------------------- 1 | package Question8_9; 2 | 3 | public class Question { 4 | 5 | public static void main(String[] args) { 6 | Directory root = new Directory("Food", null); 7 | File taco = new File("Taco", root, 4); 8 | File hamburger = new File("Hamburger", root, 9); 9 | root.addEntry(taco); 10 | root.addEntry(hamburger); 11 | 12 | Directory healthy = new Directory("Healthy", root); 13 | 14 | Directory fruits = new Directory("Fruits", healthy); 15 | File apple = new File("Apple", fruits, 5); 16 | File banana = new File("Banana", fruits, 6); 17 | fruits.addEntry(apple); 18 | fruits.addEntry(banana); 19 | 20 | healthy.addEntry(fruits); 21 | 22 | Directory veggies = new Directory("Veggies", healthy); 23 | File carrot = new File("Carrot", veggies, 6); 24 | File lettuce = new File("Lettuce", veggies, 7); 25 | File peas = new File("Peas", veggies, 4); 26 | veggies.addEntry(carrot); 27 | veggies.addEntry(lettuce); 28 | veggies.addEntry(peas); 29 | 30 | healthy.addEntry(veggies); 31 | 32 | root.addEntry(healthy); 33 | 34 | System.out.println(root.numberOfFiles()); 35 | System.out.println(veggies.getFullPath()); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /java/Chapter 9/Introduction/FibonacciFB.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class FibonacciFB { 4 | public static int max = 100; // Make this as big as you want! (Though you'll exceed the bounds of a long around 46) 5 | public static int[] fib = new int[max]; 6 | public static int fibonacci(int i) { 7 | if (i == 0) { 8 | return 0; 9 | } 10 | if (i == 1) { 11 | return 1; 12 | } 13 | if (fib[i] != 0) { 14 | return fib[i]; 15 | } 16 | fib[i] = fibonacci(i - 1) + fibonacci(i - 2); 17 | return fib[i]; 18 | } 19 | 20 | /** 21 | * @param args 22 | */ 23 | public static void main(String[] args) { 24 | int trials = 10; // Run code multiple times to compute average time. 25 | double[] times = new double[max]; // Store times 26 | 27 | for (int j = 0; j < trials; j++) { // Run this 10 times to compute 28 | for (int i = 0; i < max; i++) { 29 | fib = new int[max]; 30 | long start = System.currentTimeMillis(); 31 | fibonacci(i); 32 | long end = System.currentTimeMillis(); 33 | long time = end - start; 34 | times[i] += time; 35 | } 36 | } 37 | 38 | for (int j = 0; j < max; j++) { 39 | System.out.println(j + ": " + times[j] / trials + "ms"); 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /dart/Chapter11/Question11_1/question.dart: -------------------------------------------------------------------------------- 1 | /** 2 | * Merges array 3 | * a first array 4 | * b second array 5 | * lastA number of "real" elements in a 6 | * lastB number of "real" elements in b 7 | */ 8 | void merge(List a, List b, int lastA, int lastB) { 9 | int indexMerged = lastB + lastA - 1; /* Index of last location of merged array */ 10 | int indexA = lastA - 1; /* Index of last element in array a */ 11 | int indexB = lastB - 1; /* Index of last element in array b */ 12 | 13 | /* Merge a and b, starting from the last element in each */ 14 | while (indexA >= 0 && indexB >= 0) { 15 | if (a[indexA] > b[indexB]) { /* end of a is bigger than end of b */ 16 | a[indexMerged] = a[indexA]; // copy element 17 | indexMerged--; // Move indices 18 | indexA--; 19 | } else { 20 | a[indexMerged] = b[indexB]; // Copy element 21 | indexMerged--; // move indices 22 | indexB--; 23 | } 24 | } 25 | 26 | /* Copy remaining elements from b into place */ 27 | while (indexB >= 0) { 28 | a[indexMerged] = b[indexB]; 29 | indexMerged--; 30 | indexB--; 31 | } 32 | } 33 | 34 | void main() { 35 | List a = [1, 3, 4, 5, 6, 8, 10, 0, 0, 0, 0, 0]; 36 | List b = [4, 7, 9, 10, 12]; 37 | merge(a, b, 7, 5); 38 | print(a); 39 | } -------------------------------------------------------------------------------- /dart/Chapter4/Question4_1/question_improved.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import '../../utils/tree_node.dart'; 4 | 5 | int checkHeight(TreeNode root) { 6 | if (root == null) { 7 | return 0; 8 | } 9 | 10 | int leftHeight = checkHeight(root.left); 11 | if (leftHeight == -1) { 12 | return -1; 13 | } 14 | 15 | int rightHeight = checkHeight(root.right); 16 | if (rightHeight == -1) { 17 | return -1; 18 | } 19 | 20 | int heightDiff = leftHeight - rightHeight; 21 | if (heightDiff.abs() > 1) { 22 | return -1; 23 | } else { 24 | return max(leftHeight, rightHeight) + 1; 25 | } 26 | } 27 | 28 | bool isBalanced(TreeNode root) { 29 | if (checkHeight(root) == -1) { 30 | return false; 31 | } else { 32 | return true; 33 | } 34 | } 35 | 36 | void main() { 37 | // Create balanced tree 38 | List array = [0, 1, 2, 3, 5, 6, 7, 8, 9, 10]; 39 | TreeNode root = TreeNode.createMinimalBST(array); 40 | 41 | print("Is balanced? ${isBalanced(root)}"); 42 | root.print(); 43 | 44 | root.insertInOrder(-1); // Add 4 to make it unbalanced 45 | print("Is balanced? ${isBalanced(root)}"); 46 | root.print(); 47 | 48 | root.insertInOrder(-1 + 4); // Add 4 to make it unbalanced 49 | print("Is balanced? ${isBalanced(root)}"); 50 | root.print(); 51 | } -------------------------------------------------------------------------------- /dart/Chapter9/Question9_1/question.dart: -------------------------------------------------------------------------------- 1 | 2 | Stopwatch sw = new Stopwatch(); 3 | 4 | int countWaysDP(int n, List map) { 5 | if (n < 0) { 6 | return 0; 7 | } else if (n == 0) { 8 | return 1; 9 | } else if (map[n] > -1) { 10 | return map[n]; 11 | } else { 12 | map[n] = countWaysDP(n - 1, map) 13 | + countWaysDP(n - 2, map) 14 | + countWaysDP(n - 3, map); 15 | return map[n]; 16 | } 17 | 18 | } 19 | 20 | int countWaysRecursive(int n) { 21 | if (n < 0) { 22 | return 0; 23 | } else if (n == 0) { 24 | return 1; 25 | } else { 26 | return countWaysRecursive(n - 1) + countWaysRecursive(n - 2) + countWaysRecursive(n - 3); 27 | } 28 | } 29 | 30 | void main() { 31 | for (int i = 0; i < 30; i++) { 32 | sw.start(); 33 | int t1 = sw.elapsedMilliseconds; 34 | List map = new List(30 + 1); 35 | for (int j = 0; j < map.length; j++) { 36 | map[j] = -1; 37 | } 38 | 39 | int c1 = countWaysDP(i, map); 40 | int t2 = sw.elapsedMilliseconds; 41 | int d1 = t2 - t1; 42 | 43 | int t3 = sw.elapsedMilliseconds; 44 | int c2 = countWaysRecursive(i); 45 | int t4 = sw.elapsedMilliseconds; 46 | int d2 = t4 - t3; 47 | print("$i $c1 $c2 $d1 $d2"); 48 | sw.stop(); 49 | sw.reset(); 50 | } 51 | } -------------------------------------------------------------------------------- /java/Introduction/CompareBinaryToHex/CompareBinaryToHex.java: -------------------------------------------------------------------------------- 1 | package CompareBinaryToHex; 2 | 3 | public class CompareBinaryToHex { 4 | 5 | public static int digitToValue(char c) { 6 | if (c >= '0' && c <= '9') { 7 | return c - '0'; 8 | } else if (c >= 'A' && c <= 'F') { 9 | return 10 + c - 'A'; 10 | } else if (c >= 'a' && c <= 'f') { 11 | return 10 + c - 'a'; 12 | } 13 | return -1; 14 | } 15 | 16 | public static int convertToBase(String number, int base) { 17 | if (base < 2 || (base > 10 && base != 16)) return -1; 18 | int value = 0; 19 | for (int i = number.length() - 1; i >= 0; i--) { 20 | int digit = digitToValue(number.charAt(i)); 21 | if (digit < 0 || digit >= base) { 22 | return -1; 23 | } 24 | int exp = number.length() - 1 - i; 25 | value += digit * Math.pow(base, exp); 26 | } 27 | return value; 28 | } 29 | 30 | public static boolean compareBinToHex(String binary, String hex) { 31 | int n1 = convertToBase(binary, 2); 32 | int n2 = convertToBase(hex, 16); 33 | if (n1 < 0 || n2 < 0) { 34 | return false; 35 | } else { 36 | return n1 == n2; 37 | } 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(compareBinToHex("111001011", "1CB")); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_5/testcompress.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from compress import * 3 | 4 | class TestCompress(unittest.TestCase): 5 | def testEmpty(self): 6 | '''compress must return empty for empty strings''' 7 | self.assertEqual('', compress('')) 8 | 9 | def testSingle(self): 10 | '''compress must return the original string for single character strings''' 11 | self.assertEqual('a', compress('a')) 12 | 13 | def testCompress(self): 14 | '''compress must return the expected output for known strings''' 15 | words = ( ('aaaabbbccd', 'a4b3c2d1'), 16 | ('aaabbbbccd', 'a3b4c2d1'), 17 | ('abccccdddeeeee', 'a1b1c4d3e5') ) 18 | for (orig, expected) in words: 19 | e = compress(orig) 20 | self.assertEqual(expected, e) 21 | 22 | def testNoCompress(self): 23 | '''compress must not compress strings that turn out to have length >= than the original''' 24 | words = ( ('aabc', 'aabc'), 25 | ('abbbc', 'abbbc'), 26 | ('abccdee', 'abccdee') ) 27 | for (orig, expected) in words: 28 | e = compress(orig) 29 | self.assertEqual(expected, e) 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | 34 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_1/QuestionImproved.java: -------------------------------------------------------------------------------- 1 | package Question4_1; 2 | import CtCILibrary.TreeNode; 3 | 4 | public class QuestionImproved { 5 | 6 | public static int checkHeight(TreeNode root) { 7 | if (root == null) { 8 | return 0; 9 | } 10 | int leftHeight = checkHeight(root.left); 11 | if (leftHeight == -1) { 12 | return -1; 13 | } 14 | int rightHeight = checkHeight(root.right); 15 | if (rightHeight == -1) { 16 | return -1; 17 | } 18 | 19 | int heightDiff = leftHeight - rightHeight; 20 | if (Math.abs(heightDiff) > 1) { 21 | return -1; 22 | } 23 | else { 24 | return Math.max(leftHeight, rightHeight) + 1; 25 | } 26 | } 27 | 28 | public static boolean isBalanced(TreeNode root) { 29 | if (checkHeight(root) == -1) { 30 | return false; 31 | } else { 32 | return true; 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | // Create balanced tree 38 | int[] array = {0, 1, 2, 3, 5, 6, 7, 8, 9, 10}; 39 | TreeNode root = TreeNode.createMinimalBST(array); 40 | 41 | 42 | System.out.println("Is balanced? " + isBalanced(root)); 43 | 44 | root.insertInOrder(-1); // Add 4 to make it unbalanced 45 | 46 | System.out.println("Is balanced? " + isBalanced(root)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Call.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | /* Represents a call from a user. Calls have a minimum rank and are assigned to the 4 | * first employee who can handle that call. 5 | */ 6 | public class Call { 7 | /* Minimal rank of employee who can handle this call. */ 8 | private Rank rank; 9 | 10 | /* Person who is calling. */ 11 | private Caller caller; 12 | 13 | /* Employee who is handling call. */ 14 | private Employee handler; 15 | 16 | public Call(Caller c) { 17 | rank = Rank.Responder; 18 | caller = c; 19 | } 20 | 21 | /* Set employee who is handling call. */ 22 | public void setHandler(Employee e) { 23 | handler = e; 24 | } 25 | 26 | /* Play recorded message to the customer. */ 27 | public void reply(String message) { 28 | System.out.println(message); 29 | } 30 | 31 | public Rank getRank() { 32 | return rank; 33 | } 34 | 35 | public void setRank(Rank r) { 36 | rank = r; 37 | } 38 | 39 | public Rank incrementRank() { 40 | if (rank == Rank.Responder) { 41 | rank = Rank.Manager; 42 | } else if (rank == Rank.Manager) { 43 | rank = Rank.Director; 44 | } 45 | return rank; 46 | } 47 | 48 | /* Disconnect call. */ 49 | public void disconnect() { 50 | reply("Thank you for calling"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /dart/Chapter1/Question1_7/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Write an algorithm such that if an element in an MxN matrix is 0, 3 | * its entire row and column are set to 0. 4 | */ 5 | import '../../utils/assorted_methods.dart'; 6 | void setZeros(List> matrix) { 7 | List row = new List(matrix.length); 8 | List column = new List(matrix[0].length); 9 | 10 | // Dart does not default to false. 11 | for (int i = 0; i < row.length; i++) { 12 | row[i] = false; 13 | } 14 | for (int i = 0; i < column.length; i++) { 15 | column[i] = false; 16 | } 17 | 18 | // Store the row and column index with value 0 19 | for (int i = 0; i < matrix.length; i++) { 20 | for (int j = 0; j < matrix[0].length; j++) { 21 | if (matrix[i][j] == 0) { 22 | row[i] = true; 23 | column[j] = true; 24 | } 25 | } 26 | } 27 | 28 | // Set arr[i][j] to 0 if either row i or column j has a 0 29 | for (int i = 0; i < matrix.length; i++) { 30 | for (int j = 0; j < matrix[0].length; j++) { 31 | if (row[i] || column[j]) { 32 | matrix[i][j] = 0; 33 | } 34 | } 35 | } 36 | } 37 | 38 | void main() { 39 | List> matrix = randomMatrix(3, 5, 0, 5); 40 | printIntMatrix(matrix); 41 | setZeros(matrix); 42 | print("\n"); 43 | printIntMatrix(matrix); 44 | } -------------------------------------------------------------------------------- /java/Chapter 9/Question9_5/Question.java: -------------------------------------------------------------------------------- 1 | package Question9_5; 2 | 3 | import java.util.*; 4 | 5 | public class Question { 6 | 7 | public static ArrayList getPerms(String str) { 8 | if (str == null) { 9 | return null; 10 | } 11 | ArrayList permutations = new ArrayList(); 12 | if (str.length() == 0) { // base case 13 | permutations.add(""); 14 | return permutations; 15 | } 16 | 17 | char first = str.charAt(0); // get the first character 18 | String remainder = str.substring(1); // remove the first character 19 | ArrayList words = getPerms(remainder); 20 | for (String word : words) { 21 | for (int j = 0; j <= word.length(); j++) { 22 | String s = insertCharAt(word, first, j); 23 | permutations.add(s); 24 | } 25 | } 26 | return permutations; 27 | } 28 | 29 | public static String insertCharAt(String word, char c, int i) { 30 | String start = word.substring(0, i); 31 | String end = word.substring(i); 32 | return start + c + end; 33 | } 34 | 35 | public static void main(String[] args) { 36 | ArrayList list = getPerms("abcde"); 37 | System.out.println("There are " + list.size() + " permutations."); 38 | for (String s : list) { 39 | System.out.println(s); 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_8/testRotation.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from rotation import * 3 | 4 | class TestRotation(unittest.TestCase): 5 | def testEmpty(self): 6 | '''isRotation must return false for empty strings''' 7 | self.assertFalse(isRotation('', '')) 8 | 9 | def testSingle(self): 10 | '''isRotation must return true for single same-character strings''' 11 | self.assertTrue(isRotation('a', 'a')) 12 | 13 | def testDouble(self): 14 | '''isRotation must return true for double same-character strings''' 15 | self.assertTrue(isRotation('ab', 'ab')) 16 | 17 | def testTrue(self): 18 | '''isRotation must return true for known rotation strings''' 19 | words = ( ('erbottlewat', 'waterbottle'), 20 | ('hello', 'hello') ) 21 | 22 | for w1, w2 in words: 23 | self.assertTrue(isRotation(w1, w2)) 24 | 25 | def testFalse(self): 26 | '''isRotation must return true for known non-rotation strings''' 27 | words = ( ('erbottlewa', 'waterbottle'), 28 | ('nick', 'nik'), 29 | ('hello', 'hello w') ) 30 | 31 | for w1, w2 in words: 32 | self.assertFalse(isRotation(w1, w2)) 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /python/Chapter 2/Question2_6.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | 4 | def findBeginning(linkedlist): 5 | slow = linkedlist.head 6 | fast = linkedlist.head 7 | 8 | # Find meetng point 9 | while (fast != None) and (fast.next != None): 10 | slow = slow.next 11 | fast = fast.next.next 12 | if fast == slow: 13 | break 14 | 15 | # Check whether it is a circular linked list 16 | if fast == None or fast.next == None: 17 | return None 18 | 19 | # Move one runner to head. Making them move at same pace, they will meet at the beginning of the loop 20 | fast = linkedlist.head 21 | while fast != slow: 22 | slow = slow.next 23 | fast = fast.next 24 | 25 | return fast 26 | 27 | 28 | 29 | # -----------------test------------------ 30 | nodes_number = 100 31 | nodes_in_loop = 20 32 | L = LinkedList() 33 | current = L.head 34 | store = [] # store nodes to help creating loop 35 | 36 | # Create a linked list 37 | for i in range(nodes_number): 38 | L.addNode(i) 39 | current = L.head if i==0 else current.next 40 | store.append(current) 41 | 42 | # Creat loop 43 | current.next = None if nodes_in_loop <= 0 else store[nodes_number - nodes_in_loop] 44 | 45 | beginning = findBeginning(L) 46 | print beginning # 80 47 | -------------------------------------------------------------------------------- /python/Chapter 4/Question4_3/ChapQ4.3.py: -------------------------------------------------------------------------------- 1 | #binary tree python 2 | class BinaryTree: 3 | def __init__(self, content, left = None, right = None): 4 | self.content = content 5 | self.left = left 6 | self.right = right 7 | 8 | def __str__(self): 9 | return "( " + str(self.content) + " ( " + str(self.left) + " | " + str(self.right) + "))" 10 | 11 | #Given a sorted (increasing order) array with unique integer elements, write an 12 | #algorithm to create a binary search tree with minimal height. 13 | 14 | 15 | def int_array_to_binary_search_tree(intarray): 16 | #use the middle of the array to divide it. this ensures minimal height. 17 | if len(intarray) == 0: 18 | return None 19 | if len(intarray) == 1: 20 | return BinaryTree(intarray[0]) 21 | cut = len(intarray) / 2 22 | return BinaryTree( intarray[cut], \ 23 | int_array_to_binary_search_tree(intarray[0:cut]), 24 | int_array_to_binary_search_tree(intarray[cut+1:])) 25 | 26 | #testing 27 | 28 | intarray1=[1,2,3,4,5,6,7,8,9,10,12,15,18,22,43,144,515] 29 | intarray2=[1,2,3,4,5,6,7,8,9,10,12,15,18,22,43,144,515,4123] 30 | 31 | print str(int_array_to_binary_search_tree(intarray1)) 32 | 33 | print str(int_array_to_binary_search_tree(intarray2)) 34 | 35 | #we could benefit from a better tree visualization here 36 | --------------------------------------------------------------------------------