├── .gitignore ├── Chapter01 ├── C# │ ├── BooleanType.cs │ ├── IntegerTypes.cs │ └── StringType.cs ├── Java │ ├── BooleanType.java │ ├── IntegerTypes.java │ └── StringType.java ├── Objective-C │ ├── EDSBooleanType.h │ ├── EDSBooleanType.m │ ├── EDSFloatingTypes.m │ ├── EDSIntegerTypes.h │ ├── EDSIntegerTypes.m │ ├── EDSStringType.h │ └── EDSStringType.m └── Swift │ ├── BoolType.swift │ ├── IntegerTypes.swift │ └── StringType.swift ├── Chapter02 ├── C# │ └── LoggedInUserArray.cs ├── Java │ └── LoggedInUserArray.java ├── Objective-C │ ├── EDSLoggedInUserArray.h │ └── EDSLoggedInUserArray.m └── Swift │ └── LoggedInUserArray.swift ├── Chapter03 ├── C# │ ├── LoggedInUserList.cs │ └── WaypointList.cs ├── Java │ ├── LoggedInUserList.java │ └── WaypointList.java ├── Objective-C │ ├── EDSLoggedInUserList.h │ ├── EDSLoggedInUserList.m │ ├── EDSWaypointList.h │ └── EDSWaypointList.m └── Swift │ ├── LoggedInUserList.swift │ └── WaypointList.swift ├── Chapter04 ├── C# │ └── CommandStack.cs ├── Java │ └── CommandStack.java ├── Objective-C │ ├── EDSCommandStack.h │ └── EDSCommandStack.m └── Swift │ └── CommandStack.swift ├── Chapter05 ├── C# │ └── CustomerQueue.cs ├── Java │ └── CustomerQueue.java ├── Objective-C │ ├── EDSCustomerQueue.h │ └── EDSCustomerQueue.m └── Swift │ └── CustomerQueue.swift ├── Chapter06 ├── C# │ └── PointsDictionary.cs ├── Java │ └── PointsDictionary.java ├── Objective-C │ ├── EDSPointsDictionary.h │ └── EDSPointsDictionary.m └── Swift │ └── PointsDictionary.swift ├── Chapter07 ├── C# │ ├── LoggedInUserSet.cs │ └── PlaylistSet.cs ├── Java │ ├── LoggedInUserSet.java │ └── PlaylistSet.java ├── Objective-C │ ├── EDSLoggedInUserSet.h │ ├── EDSLoggedInUserSet.m │ ├── EDSPlaylistSet.h │ └── EDSPlaylistSet.m └── Swift │ ├── LoggedInUserSet.swift │ └── PlaylistSet.swift ├── Chapter08 ├── C# │ ├── SilverLine.cs │ └── WaypointList.cs ├── Java │ ├── SilverLine.java │ └── Waypoint.java ├── Objective-C │ ├── EDSWaypoint.h │ ├── EDSWaypoint.m │ ├── SilverLine.h │ └── SilverLine.m └── Swift │ ├── SilverLine.swift │ └── Waypoint.swift ├── Chapter09 ├── C# │ └── Node.cs ├── Java │ └── Node.java ├── Objective-C │ ├── EDSNode.h │ └── EDSNode.m └── Swift │ └── Node.swift ├── Chapter10 ├── C# │ └── Heap.cs ├── Java │ ├── HeapNode.java │ └── MinHeap.java ├── Objective-C │ ├── EDSMinHeap.h │ └── EDSMinHeap.m └── Swift │ └── MinHeap.swift ├── Chapter11 ├── C# │ ├── Graph.cs │ └── GraphNode.cs ├── Java │ ├── Graph.java │ └── GraphNode.java ├── Objective-C │ ├── EDSGraph.h │ ├── EDSGraph.m │ ├── EDSGraphNode.h │ └── EDSGraphNode.m └── Swift │ ├── Graph.swift │ └── GraphNode.swift ├── Chapter12 ├── C# │ └── ArraySortingAlgorithms.cs ├── Java │ ├── ArraySortingAlgorithms.java │ └── main.java ├── Objective-C │ ├── EDSArraySortingAlgorithms.h │ ├── EDSArraySortingAlgorithms.m │ └── main.m └── Swift │ ├── ArraySortingAlgorithms.swift │ └── main.swift ├── Chapter13 ├── C# │ └── ArraySearchAlgorithms.cs ├── Java │ ├── ArraySearchAlgorithms.java │ └── main.java ├── Objective-C │ ├── EDSArraySearchAlgorithms.h │ ├── EDSArraySearchAlgorithms.m │ └── main.m └── Swift │ ├── ArraySearchAlgorithms.swift │ └── main.swift ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /Chapter01/C#/BooleanType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace EverydayDataStructures 3 | { 4 | public class BooleanType 5 | { 6 | public BooleanType() 7 | { 8 | } 9 | 10 | public static void boolDemo() 11 | { 12 | //C# 13 | bool a = true; 14 | bool b = false; 15 | bool c = a; 16 | 17 | Console.WriteLine("a: {0}", a); 18 | Console.WriteLine("b: {0}", b); 19 | Console.WriteLine("c: {0}", c); 20 | 21 | //Operators 22 | Console.WriteLine("a AND b: {0}", a && b); 23 | Console.WriteLine("a OR b: {0}", a || b); 24 | Console.WriteLine("NOT a: {0}", !a); 25 | Console.WriteLine("NOT b: {0}", !b); 26 | Console.WriteLine("a XOR b: {0}", a ^ b); 27 | 28 | //Order of precedence & short circuiting 29 | Console.WriteLine("(c OR b) AND a: {0}", (c || b) && a); 30 | } 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Chapter01/C#/IntegerTypes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace EverydayDataStructures 3 | { 4 | public class IntegerTypes 5 | { 6 | public IntegerTypes() 7 | { 8 | } 9 | 10 | public static void intDemo() 11 | { 12 | sbyte minSbyte = -128; 13 | byte maxByte = 255; 14 | Console.WriteLine("minSbyte: {0}", minSbyte); 15 | Console.WriteLine("maxByte: {0}", maxByte); 16 | 17 | short minShort = -32768; 18 | ushort maxUShort = 65535; 19 | Console.WriteLine("minShort: {0}", minShort); 20 | Console.WriteLine("maxUShort: {0}", maxUShort); 21 | 22 | int minInt = -2147483648; 23 | uint maxUint = 4294967295; 24 | Console.WriteLine("minInt: {0}", minInt); 25 | Console.WriteLine("maxUint: {0}", maxUint); 26 | 27 | long minLong = -9223372036854775808; 28 | ulong maxUlong = 18446744073709551615; 29 | Console.WriteLine("minLong: {0}", minLong); 30 | Console.WriteLine("maxUlong: {0}", maxUlong); 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /Chapter01/C#/StringType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace EverydayDataStructures 3 | { 4 | public class StringType 5 | { 6 | public StringType() 7 | { 8 | } 9 | 10 | public static void stringDemo() 11 | { 12 | //C# 13 | string one = "One String"; 14 | Console.WriteLine("One: {0}", one); 15 | 16 | String two = "Two String"; 17 | Console.WriteLine("Two: {0}", two); 18 | 19 | String red = "Red String"; 20 | Console.WriteLine("Red: {0}", red); 21 | 22 | String blue = "Blue String"; 23 | Console.WriteLine("Blue: {0}", blue); 24 | 25 | String purple = red + blue; 26 | Console.WriteLine("Concatenation: {0}", purple); 27 | 28 | purple = "Purple String"; 29 | Console.WriteLine("Whoops! Mutation: {0}", purple); 30 | } 31 | 32 | public static void arrayDemo() 33 | { 34 | User u1 = new User("Will", 1); 35 | User u2 = new User("Dorothy", 2); 36 | User u3 = new User("Sam", 3); 37 | User u4 = new User("Logan", 4); 38 | User u5 = new User("Lucas", 5); 39 | User u6 = new User("Zion", 6); 40 | LoggedInUserArray users = new LoggedInUserArray(); 41 | 42 | users.UserAuthenticated(u1); 43 | users.UserAuthenticated(u2); 44 | users.UserAuthenticated(u3); 45 | users.UserAuthenticated(u4); 46 | users.UserLoggedOut(u2); 47 | users.UserAuthenticated(u5); 48 | users.UserAuthenticated(u6); 49 | 50 | 51 | } 52 | } 53 | } 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Chapter01/Java/BooleanType.java: -------------------------------------------------------------------------------- 1 | 2 | package main.java; 3 | /** 4 | * Created by willsmith on 8/11/16. 5 | */ 6 | public class BooleanType 7 | { 8 | public static void boolDemo() 9 | { 10 | //Java 11 | boolean a = true; 12 | boolean b = false; 13 | boolean c = a; 14 | 15 | System.out.println("a: " + a); 16 | System.out.println("b: " + b); 17 | System.out.println("c: " + c); 18 | System.out.println("a AND b: " + (a && b)); 19 | System.out.println("a OR b: " + (a || b)); 20 | System.out.println("NOT a: " + !a); 21 | System.out.println("NOT b: " + !b); 22 | System.out.println("a XOR b: " + (a ^ b)); 23 | System.out.println("(c OR b) AND a: " + ((c || b) && a)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter01/Java/IntegerTypes.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /* 4 | * To change this license header, choose License Headers in Project Properties. 5 | * To change this template file, choose Tools | Templates 6 | * and open the template in the editor. 7 | */ 8 | 9 | /** 10 | * 11 | * @author willsmith 12 | */ 13 | public class IntegerTypes { 14 | 15 | public static void intDemo() 16 | { 17 | byte myByte = -128; 18 | byte bigByte = 127; 19 | 20 | //Byte class 21 | Byte minByte = new Byte(myByte); 22 | Byte maxByte = new Byte("127"); 23 | System.out.println(minByte); 24 | System.out.println(bigByte); 25 | System.out.println(maxByte); 26 | 27 | short myShort = -32768; 28 | short bigShort = 32767; 29 | 30 | //Short class 31 | Short minShort = new Short(myShort); 32 | Short maxShort = new Short("32767"); 33 | System.out.println(minShort); 34 | System.out.println(bigShort); 35 | System.out.println(maxShort); 36 | 37 | int myInt = -2147483648; 38 | int bigInt = 2147483647; 39 | 40 | //Integer class 41 | Integer minInt = new Integer(myInt); 42 | Integer maxInt = new Integer("2147483647"); 43 | System.out.println(minInt); 44 | System.out.println(bigInt); 45 | System.out.println(maxInt); 46 | 47 | long myLong = -9223372036854775808L; 48 | long bigLong = 9223372036854775807L; 49 | 50 | //Long class 51 | Long minLong = new Long(myLong); 52 | Long maxLong = new Long("9223372036854775807"); 53 | System.out.println(minLong); 54 | System.out.println(bigLong); 55 | System.out.println(maxLong); 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Chapter01/Java/StringType.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /** 4 | * Created by willsmith on 8/11/16. 5 | */ 6 | public class StringType 7 | { 8 | public static void stringDemo() 9 | { 10 | //Java 11 | String one = "One String"; 12 | System.out.println("One: " + one); 13 | 14 | String two = "Two String"; 15 | System.out.println("Two: " + two); 16 | 17 | String red = "Red String"; 18 | System.out.println("Red: " + red); 19 | 20 | String blue = "Blue String"; 21 | System.out.println("Blue: " + blue); 22 | 23 | String purple = red + blue; 24 | System.out.println("Concatenation: " + purple); 25 | 26 | purple = "Purple String"; 27 | System.out.println("Whoops! Mutation: " + purple); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSBooleanType.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSBooleanType.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSBooleanType : NSObject 12 | 13 | +(void)boolDemo; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSBooleanType.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSBooleanType.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSBooleanType.h" 10 | 11 | @implementation EDSBooleanType 12 | 13 | +(void)boolDemo 14 | { 15 | BOOL a = YES; 16 | BOOL b = NO; 17 | BOOL c = a; 18 | 19 | NSLog(@"a: %hhd", a); 20 | NSLog(@"b: %hhd", b); 21 | NSLog(@"c: %hhd", c); 22 | NSLog(@"a AND b: %d", a && b); 23 | NSLog(@"a OR b: %d", a || b); 24 | NSLog(@"NOT a: %d", !a); 25 | NSLog(@"NOT b: %d", !b); 26 | NSLog(@"a XOR b: %d", a ^ b); 27 | NSLog(@"(c OR b) AND a: %d", (c || b) && a); 28 | } 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSFloatingTypes.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSFloatingTypes.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/9/16. 6 | // Copyright © 2016 William Smith. All rights reserved. 7 | // 8 | 9 | #import "EDSFloatingTypes.h" 10 | 11 | @implementation EDSFloatingTypes 12 | 13 | +(void)floatDemo 14 | { 15 | float piFloat = 3.14159265358979323846264338327f; 16 | NSLog(@"piFloat: %f", piFloat); 17 | 18 | NSNumber *floatNumber = [NSNumber numberWithFloat:piFloat]; 19 | NSLog(@"floatNumber: %@", [floatNumber stringValue]); 20 | 21 | double piDouble = 3.14159265358979323846264338327; 22 | NSLog(@"piDouble: %.15f", piDouble); 23 | 24 | NSNumber *doubleNumber = [NSNumber numberWithDouble:piDouble]; 25 | NSLog(@"doubleNumber: %@", [doubleNumber stringValue]); 26 | 27 | NSDecimalNumber *piDecimalNumber = [[NSDecimalNumber alloc] initWithDouble:3.14159265358979323846264338327]; 28 | NSLog(@"piDecimalNumber: %@", [piDecimalNumber stringValue]); 29 | } 30 | 31 | @end 32 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSIntegerTypes.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSIntegerTypes.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/4/16. 6 | // Copyright © 2016 William Smith. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSIntegerTypes : NSObject 12 | 13 | + (void)intDemo; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSIntegerTypes.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSIntegerTypes.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/4/16. 6 | // Copyright © 2016 William Smith. All rights reserved. 7 | // 8 | 9 | #import "EDSIntegerTypes.h" 10 | 11 | @implementation EDSIntegerTypes 12 | 13 | +(void)intDemo 14 | { 15 | char number = -127; 16 | unsigned char uNumber = 255; 17 | NSLog(@"Signed char number: %hhd", number); 18 | NSLog(@"Unsigned char uNumber: %hhu", uNumber); 19 | 20 | int8_t fixedNumber8 = -127; 21 | uint8_t fixedUNumber8 = 255; 22 | NSLog(@"fixedNumber8: %hhd", fixedNumber8); 23 | NSLog(@"fixedUNumber8: %hhu", fixedUNumber8); 24 | 25 | NSNumber *charNumber = [NSNumber numberWithChar:number]; 26 | NSLog(@"Char charNumber: %@", [charNumber stringValue]); 27 | 28 | short aShort = -32768; 29 | unsigned short anUnsignedShort = 65535; 30 | NSLog(@"Signed short aShort: %hd", aShort); 31 | NSLog(@"Unsigned short anUnsignedShort: %hu", anUnsignedShort); 32 | 33 | int16_t fixedNumber16 = -32768; 34 | uint16_t fixedUNumber16 = 65535; 35 | NSLog(@"fixedNumber16: %hd", fixedNumber16); 36 | NSLog(@"fixedUNumber16: %hu", fixedUNumber16); 37 | 38 | NSNumber *shortNumber = [NSNumber numberWithShort:aShort]; 39 | NSLog(@"Short shortNumber: %@", [shortNumber stringValue]); 40 | 41 | int anInt = -2147483648; 42 | unsigned int anUnsignedInt = 4294967295; 43 | NSLog(@"Signed Int anInt: %d", anInt); 44 | NSLog(@"Unsigned Int anUnsignedInt: %u", anUnsignedInt); 45 | 46 | int32_t fixedNumber32 = -2147483648; 47 | uint32_t fixedUNumber32 = 4294967295; 48 | NSLog(@"fixedNumber32: %d", fixedNumber32); 49 | NSLog(@"fixedUNumber32: %u", fixedUNumber32); 50 | 51 | NSNumber *intNumber = [NSNumber numberWithInt:anInt]; 52 | NSLog(@"Int intNumber: %@", [intNumber stringValue]); 53 | 54 | long long aLongLong = -9223372036854775808; 55 | unsigned long long anUnsignedLongLong = 18446744073709551615; 56 | NSLog(@"Signed long long aLongLong: %lld", aLongLong); 57 | NSLog(@"Unsigned long long anUnsignedLongLong: %llu", anUnsignedLongLong); 58 | 59 | int64_t fixedNumber64 = -9223372036854775808; 60 | uint64_t fixedUNumber64 = 18446744073709551615; 61 | NSLog(@"fixedNumber64: %lld", fixedNumber64); 62 | NSLog(@"fixedUNumber64: %llu", fixedUNumber64); 63 | 64 | NSNumber *longlongNumber = [NSNumber numberWithLongLong:aLongLong]; 65 | NSLog(@"Long long longlongNumber: %@", [longlongNumber stringValue]); 66 | } 67 | 68 | @end 69 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSStringType.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSStringType.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSStringType : NSObject 12 | 13 | +(void)stringDemo; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /Chapter01/Objective-C/EDSStringType.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSStringType.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSStringType.h" 10 | 11 | @implementation EDSStringType 12 | 13 | +(void) stringDemo 14 | { 15 | //Objective-C 16 | NSString *one = @"One String"; 17 | NSLog(@"One: %@", one); 18 | 19 | NSString *two = @"Two String"; 20 | NSLog(@"Two: %@", two); 21 | 22 | NSString *red = @"Red String"; 23 | NSLog(@"Red: %@", red); 24 | 25 | NSString *blue = @"Blue String"; 26 | NSLog(@"Blue: %@", blue); 27 | 28 | NSString *purple = [[NSArray arrayWithObjects:red, blue, nil] componentsJoinedByString:@""]; 29 | NSLog(@"Concatenation: %@", purple); 30 | 31 | purple = @"Purple String"; 32 | NSLog(@"Whoops! Mutation: %@", purple); 33 | 34 | } 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /Chapter01/Swift/BoolType.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BoolType.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/10/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | class BoolType 12 | { 13 | static func boolDemo() 14 | { 15 | let a : Bool = true 16 | let b : Bool = false 17 | let c = a 18 | 19 | print("a: \(a)") 20 | print("b: \(b)") 21 | print("c: \(c)") 22 | print("a AND b: \(a && b)") 23 | print("a OR b: \(a || b)") 24 | print("NOT a: \(!a)") 25 | print("NOT b: \(!b)") 26 | print("a XOR b: \(a != b)") 27 | print("(c OR b) AND a: \((c || b) && a)") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter01/Swift/IntegerTypes.swift: -------------------------------------------------------------------------------- 1 | // 2 | // IntegerTypes.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/5/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | class IntegerTypes 12 | { 13 | static func intExamples() 14 | { 15 | let int8 : Int8 = -127 16 | let uint8 : UInt8 = 255 17 | print("int8: \(int8)") 18 | print("uint8: \(uint8)") 19 | 20 | let int16 : Int16 = -32768 21 | let uint16 : UInt16 = 65535 22 | print("int16: \(int16)") 23 | print("uint16: \(uint16)") 24 | 25 | let int32 : Int32 = -2147483648 26 | let uint32 : UInt32 = 4294967295 27 | print("int32: \(int32)") 28 | print("uint32: \(uint32)") 29 | 30 | let int64 : Int64 = -9223372036854775808 31 | let uint64 : UInt64 = 18446744073709551615 32 | print("int64: \(int64)") 33 | print("uint64: \(uint64)") 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Chapter01/Swift/StringType.swift: -------------------------------------------------------------------------------- 1 | // 2 | // StringType.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | class StringType 12 | { 13 | static func stringDemo() 14 | { 15 | //Swift 16 | let one : String = "One String" 17 | print("One: \(one)") 18 | 19 | let two : String = "Two String" 20 | print("Two: \(two)") 21 | 22 | let red : String = "Red String" 23 | print("Red: \(red)") 24 | 25 | let blue : String = "Blue String" 26 | print("Blue: \(blue)") 27 | 28 | var purple : String = red + blue 29 | print("Concatenation: \(purple)") 30 | 31 | purple = "Purple String"; 32 | print("Whoops! Mutation: \(purple)") 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Chapter02/C#/LoggedInUserArray.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EverydayDataStructures 4 | { 5 | public class LoggedInUserArray 6 | { 7 | User[] _users; 8 | 9 | public LoggedInUserArray() 10 | { 11 | User[] users = new User[0]; 12 | _users = users; 13 | } 14 | 15 | bool CanAddUser(User user) 16 | { 17 | bool containsUser = false; 18 | foreach (User u in _users) 19 | { 20 | if (user == u) 21 | { 22 | containsUser = true; 23 | break; 24 | } 25 | } 26 | 27 | if (containsUser) 28 | { 29 | return false; 30 | } 31 | else 32 | { 33 | if (_users.Length >= 30) 34 | { 35 | return false; 36 | } 37 | else 38 | { 39 | return true; 40 | } 41 | } 42 | } 43 | 44 | public void UserAuthenticated(User user) 45 | { 46 | if (this.CanAddUser(user)) 47 | { 48 | Array.Resize(ref _users, _users.Length + 1); 49 | _users[_users.Length - 1] = user; 50 | Console.WriteLine("Length after adding user {0}: {1}", user.Id, _users.Length); 51 | } 52 | } 53 | 54 | public void UserLoggedOut(User user) 55 | { 56 | int index = Array.IndexOf(_users, user); 57 | if (index == -1) 58 | { 59 | Console.WriteLine("User {0} not found.", user.Id); 60 | } 61 | else 62 | { 63 | User[] newUsers = new User[_users.Length - 1]; 64 | for (int i = 0, j = 0; i < newUsers.Length - 1; i++, j++) 65 | { 66 | if (i == index) 67 | { 68 | j++; 69 | } 70 | newUsers[i] = _users[j]; 71 | } 72 | 73 | _users = newUsers; 74 | } 75 | Console.WriteLine("Length after logging out user {0}: {1}", user.Id, _users.Length); 76 | } 77 | } 78 | } 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /Chapter02/Java/LoggedInUserArray.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.Arrays; 4 | import java.util.ArrayList; 5 | 6 | /** 7 | * Created by William Smith on 8/20/16. 8 | */ 9 | public class LoggedInUserArray 10 | { 11 | User[] _users; 12 | 13 | public LoggedInUserArray() 14 | { 15 | User[] users = new User[0]; 16 | _users = users; 17 | } 18 | 19 | boolean CanAddUser(User user) 20 | { 21 | boolean containsUser = false; 22 | for (User u : _users) 23 | { 24 | if (user == u) 25 | { 26 | containsUser = true; 27 | break; 28 | } 29 | } 30 | 31 | if (containsUser) 32 | { 33 | return false; 34 | } 35 | else 36 | { 37 | ArrayList myArray = new ArrayList(); 38 | if (_users.length >= 30) 39 | { 40 | return false; 41 | } 42 | else 43 | { 44 | return true; 45 | } 46 | } 47 | } 48 | 49 | public void UserAuthenticated(User user) 50 | { 51 | if (this.CanAddUser(user)) 52 | { 53 | _users = Arrays.copyOf(_users, _users.length + 1); 54 | _users[_users.length - 1] = user; 55 | System.out.println("Length after adding user " + user.GetId() + ": " + _users.length); 56 | } 57 | } 58 | 59 | public void UserLoggedOut(User user) 60 | { 61 | int index = -1; 62 | int k = 0; 63 | for (User u : _users) 64 | { 65 | if (user == u) 66 | { 67 | index = k; 68 | break; 69 | } 70 | k++; 71 | } 72 | 73 | if (index == -1) 74 | { 75 | System.out.println("User " + user.GetId() + " not found."); 76 | } 77 | else 78 | { 79 | User[] newUsers = new User[_users.length - 1]; 80 | for (int i = 0, j = 0; i < newUsers.length - 1; i++, j++) 81 | { 82 | if (i == index) 83 | { 84 | j++; 85 | } 86 | newUsers[i] = _users[j]; 87 | } 88 | 89 | _users = newUsers; 90 | } 91 | 92 | System.out.println("Length after logging out user " + user.GetId() + ": " + _users.length); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Chapter02/Objective-C/EDSLoggedInUserArray.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSLoggedInUserArray.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/21/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSUser; 12 | 13 | @interface EDSLoggedInUserArray : NSObject 14 | 15 | -(void)userAuthenticated:(EDSUser*)user; 16 | 17 | -(void)userLoggedOut:(EDSUser*)user; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /Chapter02/Objective-C/EDSLoggedInUserArray.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSLoggedInUserArray.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/21/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSLoggedInUserArray.h" 10 | #import "EDSUser.h" 11 | 12 | @interface EDSLoggedInUserArray() 13 | { 14 | NSArray *_users; 15 | } 16 | 17 | @end 18 | 19 | @implementation EDSLoggedInUserArray 20 | 21 | -(instancetype)init 22 | { 23 | if (self = [super init]) 24 | { 25 | _users = [NSArray array]; 26 | } 27 | return self; 28 | } 29 | 30 | -(BOOL)canAddUser:(EDSUser *)user 31 | { 32 | BOOL containsUser = [_users containsObject:user]; 33 | 34 | if (containsUser) 35 | { 36 | return false; 37 | } 38 | else 39 | { 40 | if ([_users count] >= 30) 41 | { 42 | return false; 43 | } 44 | else 45 | { 46 | return true; 47 | } 48 | } 49 | } 50 | 51 | -(void)userAuthenticated:(EDSUser *)user 52 | { 53 | if ([self canAddUser:user]) 54 | { 55 | _users = [_users arrayByAddingObject:user]; 56 | NSLog(@"Length after adding user %lu: %lu", user.userId, [_users count]); 57 | } 58 | } 59 | 60 | -(void)userLoggedOut:(EDSUser *)user 61 | { 62 | NSUInteger index = [_users indexOfObject:user]; 63 | if (index == NSNotFound) 64 | { 65 | NSLog(@"User %lu not found.", user.userId); 66 | } 67 | else 68 | { 69 | NSArray *newUsers = [NSArray array]; 70 | for (EDSUser *u in _users) 71 | { 72 | if (user != u) 73 | { 74 | newUsers = [newUsers arrayByAddingObject:u]; 75 | } 76 | } 77 | 78 | _users = newUsers; 79 | } 80 | 81 | NSLog(@"Length after logging out user %lu: %lu", user.userId, [_users count]); 82 | } 83 | 84 | @end 85 | -------------------------------------------------------------------------------- /Chapter02/Swift/LoggedInUserArray.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LoggedInUserArray.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/21/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class LoggedInUserArray 12 | { 13 | var _users: Array = [User]() 14 | 15 | init() 16 | { 17 | 18 | } 19 | 20 | func canAddUser(_ user: User) -> Bool 21 | { 22 | if (_users.contains(user)) 23 | { 24 | return false 25 | } 26 | else 27 | { 28 | if (_users.count >= 30) 29 | { 30 | return false 31 | } 32 | else 33 | { 34 | return true 35 | } 36 | } 37 | } 38 | 39 | open func userAuthenticated(_ user: User) 40 | { 41 | if (self.canAddUser(user)) 42 | { 43 | _users.append(user) 44 | } 45 | 46 | print("Length after adding user \(user._userId): \(_users.count)") 47 | } 48 | 49 | open func userLoggedOut(_ user: User) 50 | { 51 | if let index = _users.index(of: user) 52 | { 53 | _users.remove(at: index) 54 | } 55 | print("Length after logging out user \(user._userId): \(_users.count)") 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Chapter03/C#/LoggedInUserList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | 5 | namespace EverydayDataStructures 6 | { 7 | public class LoggedInUserList 8 | { 9 | List _users; 10 | 11 | public LoggedInUserList() 12 | { 13 | _users = new List(); 14 | } 15 | 16 | bool CanAddUser(User user) 17 | { 18 | if (_users.Contains(user) || 19 | _users.Count >= 30) 20 | { 21 | return false; 22 | } 23 | else 24 | { 25 | return true; 26 | } 27 | } 28 | 29 | public void UserAuthenticated(User user) 30 | { 31 | if (this.CanAddUser(user)) 32 | { 33 | _users.Add(user); 34 | } 35 | } 36 | 37 | public void UserLoggedOut(User user) 38 | { 39 | _users.Remove(user); 40 | } 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Chapter03/C#/WaypointList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class WaypointList 7 | { 8 | LinkedList route; 9 | LinkedListNode current; 10 | 11 | public WaypointList() 12 | { 13 | this.route = new LinkedList(); 14 | } 15 | 16 | public void AddWaypoints(List waypoints) 17 | { 18 | foreach (Waypoint w in waypoints) 19 | { 20 | this.route.AddLast(w); 21 | } 22 | } 23 | 24 | public bool RemoveWaypoint(Waypoint waypoint) 25 | { 26 | return this.route.Remove(waypoint); 27 | } 28 | 29 | public void InsertWaypointsBefore(List waypoints, Waypoint before) 30 | { 31 | LinkedListNode node = this.route.Find(before); 32 | if (node != null) 33 | { 34 | foreach (Waypoint w in waypoints) 35 | { 36 | this.route.AddBefore(node, w); 37 | } 38 | } 39 | else 40 | { 41 | this.AddWaypoints(waypoints); 42 | } 43 | } 44 | 45 | public bool StartRoute() 46 | { 47 | if (this.route.Count > 1) 48 | { 49 | this.current = this.StartingLine(); 50 | return this.MoveToNextWaypoint(); 51 | } 52 | return false; 53 | } 54 | 55 | public bool MoveToNextWaypoint() 56 | { 57 | if (this.current != null) 58 | { 59 | this.current.Value.DeactivateWaypoint(); 60 | if (this.current != this.FinishLine()) 61 | { 62 | this.current = this.current.Next; 63 | return true; 64 | } 65 | return false; 66 | } 67 | return false; 68 | } 69 | 70 | public bool MoveToPreviousWaypoint() 71 | { 72 | if (this.current != null && 73 | this.current != this.StartingLine()) 74 | { 75 | this.current = this.current.Previous; 76 | this.current.Value.ReactivateWaypoint(); 77 | return true; 78 | } 79 | return false; 80 | } 81 | 82 | public LinkedListNode StartingLine() 83 | { 84 | return this.route.First; 85 | } 86 | 87 | public LinkedListNode FinishLine() 88 | { 89 | return this.route.Last; 90 | } 91 | 92 | public LinkedListNode CurrentWaypoint() 93 | { 94 | return this.current; 95 | } 96 | } 97 | } 98 | 99 | -------------------------------------------------------------------------------- /Chapter03/Java/LoggedInUserList.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.List; 4 | import java.util.LinkedList; 5 | 6 | 7 | /** 8 | * Created by William Smith on 8/21/16. 9 | */ 10 | public class LoggedInUserList { 11 | 12 | List _users; 13 | 14 | public LoggedInUserList() 15 | { 16 | _users = new LinkedList(); 17 | } 18 | 19 | boolean CanAddUser(User user) 20 | { 21 | if (_users.contains(user) || 22 | _users.size() >= 30) 23 | { 24 | return false; 25 | } 26 | else 27 | { 28 | return true; 29 | } 30 | } 31 | 32 | public void UserAuthenticated(User user) 33 | { 34 | if (this.CanAddUser(user)) 35 | { 36 | _users.add(user); 37 | } 38 | } 39 | 40 | public void UserLoggedOut(User user) 41 | { 42 | _users.remove(user); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Chapter03/Java/WaypointList.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.List; 4 | import java.util.LinkedList; 5 | 6 | /** 7 | * Created by William Smith on 8/25/16. 8 | */ 9 | public class WaypointList 10 | { 11 | LinkedList route; 12 | Waypoint current; 13 | 14 | public WaypointList() 15 | { 16 | this.route = new LinkedList(); 17 | } 18 | 19 | public void AddWaypoints(List waypoints) 20 | { 21 | this.route.addAll(waypoints); 22 | } 23 | 24 | public boolean RemoveWaypoint(Waypoint waypoint) 25 | { 26 | return this.route.remove(waypoint); 27 | } 28 | 29 | public void InsertWaypointsBefore(List waypoints, Waypoint before) 30 | { 31 | int index = this.route.indexOf(before); 32 | if (index >= 0) 33 | { 34 | this.route.addAll(index, waypoints); 35 | } 36 | else 37 | { 38 | this.AddWaypoints(waypoints); 39 | } 40 | } 41 | 42 | public boolean StartRoute() 43 | { 44 | if (this.route.size() > 1) 45 | { 46 | this.current = this.StartingLine(); 47 | return this.MoveToNextWaypoint(); 48 | } 49 | return false; 50 | } 51 | 52 | public boolean MoveToNextWaypoint() 53 | { 54 | if (this.current != null) 55 | { 56 | this.current.DeactivateWaypoint(); 57 | if (this.current != this.FinishLine()) 58 | { 59 | int index = this.route.indexOf(this.current); 60 | this.current = this.route.listIterator(index).next(); 61 | return true; 62 | } 63 | return false; 64 | } 65 | return false; 66 | } 67 | 68 | public boolean MoveToPreviousWaypoint() 69 | { 70 | if (this.current != null && 71 | this.current != this.StartingLine()) 72 | { 73 | int index = this.route.indexOf(this.current); 74 | this.current = this.route.listIterator(index).previous(); 75 | this.current.ReactivateWaypoint(); 76 | return true; 77 | } 78 | return false; 79 | } 80 | 81 | public Waypoint StartingLine() 82 | { 83 | return this.route.getFirst(); 84 | } 85 | 86 | public Waypoint FinishLine() 87 | { 88 | return this.route.getLast(); 89 | } 90 | 91 | public Waypoint CurrentWaypoint() 92 | { 93 | return this.current; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /Chapter03/Objective-C/EDSLoggedInUserList.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSLoggedInUserList.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/20/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSUser; 12 | 13 | @interface EDSLoggedInUserList : NSObject 14 | 15 | -(void)userAuthenticated:(EDSUser*)user; 16 | 17 | -(void)userLoggedOut:(EDSUser*)user; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /Chapter03/Objective-C/EDSLoggedInUserList.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSLoggedInUserList.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/20/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSLoggedInUserList.h" 10 | #import "EDSUser.h" 11 | 12 | @interface EDSLoggedInUserList() 13 | { 14 | NSMutableArray *_users; 15 | } 16 | 17 | @end 18 | 19 | @implementation EDSLoggedInUserList 20 | 21 | -(instancetype)init 22 | { 23 | if (self = [super init]) 24 | { 25 | _users = [NSMutableArray array]; 26 | } 27 | 28 | return self; 29 | } 30 | 31 | -(BOOL)canAddUser:(EDSUser *)user 32 | { 33 | if ([_users containsObject:user] || 34 | [_users count] >= 30) 35 | { 36 | return false; 37 | } 38 | else 39 | { 40 | return true; 41 | } 42 | } 43 | 44 | -(void)userAuthenticated:(EDSUser *)user 45 | { 46 | if ([self canAddUser:user]) 47 | { 48 | [_users addObject:user]; 49 | } 50 | } 51 | 52 | -(void)userLoggedOut:(EDSUser *)user 53 | { 54 | [_users removeObject:user]; 55 | } 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /Chapter03/Objective-C/EDSWaypointList.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSWaypointList.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/25/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | @class EDSWaypoint; 11 | 12 | @interface EDSWaypointList : NSObject 13 | 14 | @property (nonatomic,readonly) EDSWaypoint *startingLine; 15 | @property (nonatomic,readonly) EDSWaypoint *finishLine; 16 | @property (nonatomic,readonly) EDSWaypoint *currentWaypoint; 17 | 18 | -(void) addWaypoints:(NSArray*)waypoints; 19 | -(BOOL) startRoute; 20 | -(BOOL) removeWaypoint:(EDSWaypoint*)waypoint; 21 | -(void) insertWaypoints:(NSArray*)waypoints beforeWaypoint:(EDSWaypoint*)before; 22 | -(BOOL) moveToNextWaypoint; 23 | -(BOOL) moveToPreviousWaypoint; 24 | 25 | @end 26 | -------------------------------------------------------------------------------- /Chapter03/Objective-C/EDSWaypointList.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSWaypointList.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/25/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSWaypointList.h" 10 | #import "EDSWaypoint.h" 11 | 12 | @interface EDSWaypointList() 13 | { 14 | NSMutableArray *_route; 15 | EDSWaypoint *_current; 16 | } 17 | 18 | @end 19 | 20 | @implementation EDSWaypointList 21 | 22 | -(instancetype)init 23 | { 24 | if (self = [super init]) 25 | { 26 | _route = [NSMutableArray array]; 27 | } 28 | return self; 29 | } 30 | 31 | #pragma mark - Public Methods 32 | #pragma mark - 33 | -(void)addWaypoints:(NSArray *)waypoints 34 | { 35 | [_route addObjectsFromArray:waypoints]; 36 | } 37 | 38 | -(BOOL)removeWaypoint:(EDSWaypoint*)waypoint 39 | { 40 | if ([_route containsObject:waypoint]) 41 | { 42 | [_route removeObject:waypoint]; 43 | return YES; 44 | } 45 | return NO; 46 | } 47 | 48 | -(void)insertWaypoints:(NSArray *)waypoints beforeWaypoint:(EDSWaypoint*)before 49 | { 50 | NSUInteger index = [_route indexOfObject:before]; 51 | if (index == NSNotFound) 52 | { 53 | [self addWaypoints:waypoints]; 54 | } 55 | else 56 | { 57 | NSRange range = NSMakeRange(index, [waypoints count]); 58 | NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range]; 59 | [_route insertObjects:waypoints atIndexes:indexSet]; 60 | } 61 | } 62 | 63 | -(BOOL)startRoute 64 | { 65 | if ([_route count] > 1) 66 | { 67 | _current = [self startingLine]; 68 | return [self moveToNextWaypoint]; 69 | } 70 | return NO; 71 | } 72 | 73 | 74 | -(BOOL)moveToNextWaypoint 75 | { 76 | if (_current) 77 | { 78 | [_current deactivateWaypoint]; 79 | if (_current != [self finishLine]) 80 | { 81 | NSUInteger index = [_route indexOfObject:_current]; 82 | _current = [_route objectAtIndex:index+1]; 83 | return YES; 84 | } 85 | return NO; 86 | } 87 | return NO; 88 | } 89 | 90 | -(BOOL)moveToPreviousWaypoint 91 | { 92 | if (_current && 93 | _current != [self startingLine]) 94 | { 95 | NSUInteger index = [_route indexOfObject:_current]; 96 | _current = [_route objectAtIndex:index-1]; 97 | [_current reactivateWaypoint]; 98 | return YES; 99 | } 100 | return NO; 101 | } 102 | 103 | #pragma mark - Public properties 104 | #pragma mark - 105 | -(EDSWaypoint*)startingLine 106 | { 107 | return [_route firstObject]; 108 | } 109 | 110 | -(EDSWaypoint*)finishLine 111 | { 112 | return [_route lastObject]; 113 | } 114 | 115 | -(EDSWaypoint*)currentWaypoint 116 | { 117 | return _current; 118 | } 119 | 120 | @end 121 | -------------------------------------------------------------------------------- /Chapter03/Swift/LoggedInUserList.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LoggedInUserList.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/22/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class LoggedInUserList 12 | { 13 | var _users: Array = [User]() 14 | 15 | init() { } 16 | 17 | func canAddUser(_ user: User) -> Bool 18 | { 19 | if (_users.contains(user) || 20 | _users.count >= 30) 21 | { 22 | return false 23 | } 24 | else 25 | { 26 | return true 27 | } 28 | } 29 | 30 | open func userAuthenticated(_ user: User) 31 | { 32 | if (self.canAddUser(user)) 33 | { 34 | _users.append(user) 35 | } 36 | } 37 | 38 | open func userLoggedOut(_ user: User) 39 | { 40 | if let index = _users.index(of: user) 41 | { 42 | _users.remove(at: index) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Chapter03/Swift/WaypointList.swift: -------------------------------------------------------------------------------- 1 | // 2 | // WaypointList.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/26/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class WaypointList 12 | { 13 | var _route: Array = [Waypoint]() 14 | var _current: Waypoint? 15 | 16 | init() { } 17 | 18 | open func addWaypoints(_ waypoints: Array) 19 | { 20 | _route.append(contentsOf: waypoints) 21 | } 22 | 23 | open func removeWaypoint(_ waypoint: Waypoint) -> Bool 24 | { 25 | if let index = _route.index(of: waypoint) 26 | { 27 | _route.remove(at: index) 28 | return true 29 | } 30 | return false 31 | } 32 | 33 | open func insertWaypoints(_ waypoints: Array, before: Waypoint) 34 | { 35 | if let index = _route.index(of: before) 36 | { 37 | _route.insert(contentsOf: waypoints, at:index) 38 | } 39 | else 40 | { 41 | addWaypoints(waypoints) 42 | } 43 | } 44 | 45 | open func startRoute() -> Bool 46 | { 47 | if _route.count > 1 48 | { 49 | _current = startingLine() 50 | return moveToNextWaypoint() 51 | } 52 | return false 53 | } 54 | 55 | open func moveToNextWaypoint() -> Bool 56 | { 57 | if (_current != nil) 58 | { 59 | _current!.DeactivateWaypoint() 60 | if _current != self.finishLine() 61 | { 62 | let index = _route.index(of: _current!) 63 | _current = _route[index!+1] 64 | return true 65 | } 66 | return false; 67 | } 68 | return false 69 | } 70 | 71 | open func moveToPreviousWaypoint() -> Bool 72 | { 73 | if (_current != nil && 74 | _current != self.startingLine()) 75 | { 76 | let index = _route.index(of: _current!) 77 | _current = _route[index!-1] 78 | _current!.ReactivateWaypoint() 79 | return true 80 | } 81 | return false 82 | } 83 | 84 | open func startingLine() -> Waypoint 85 | { 86 | return _route.first! 87 | } 88 | 89 | open func finishLine() -> Waypoint 90 | { 91 | return _route.last! 92 | } 93 | 94 | open func currentWaypoint() -> Waypoint 95 | { 96 | return _current! 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Chapter04/C#/CommandStack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class CommandStack 7 | { 8 | public Stack _commandStack { get; private set; } 9 | int _capacity; 10 | 11 | public CommandStack(int commandCapacity) 12 | { 13 | this._commandStack = new Stack(commandCapacity); 14 | this._capacity = commandCapacity; 15 | } 16 | 17 | public bool IsFull() 18 | { 19 | return this._commandStack.Count >= this._capacity; 20 | } 21 | 22 | public bool IsEmpty() 23 | { 24 | return this._commandStack.Count == 0; 25 | } 26 | 27 | public bool PerformCommand(Command command) 28 | { 29 | if (!this.IsFull()) 30 | { 31 | this._commandStack.Push(command); 32 | return true; 33 | } 34 | return false; 35 | } 36 | 37 | public bool PerformCommands(List commands) 38 | { 39 | bool inserted = true; 40 | foreach (Command c in commands) 41 | { 42 | inserted = this.PerformCommand(c); 43 | } 44 | return inserted; 45 | } 46 | 47 | public Command UndoCommand() 48 | { 49 | return this._commandStack.Pop(); 50 | } 51 | 52 | public void Reset() 53 | { 54 | this._commandStack.Clear(); 55 | } 56 | 57 | public int TotalCommands() 58 | { 59 | return this._commandStack.Count; 60 | } 61 | } 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Chapter04/Java/CommandStack.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.EmptyStackException; 4 | import java.util.Stack; 5 | import java.util.List; 6 | 7 | 8 | /** 9 | * Created by William Smith on 8/28/16. 10 | */ 11 | 12 | public class CommandStack { 13 | private Stack _commandStack; 14 | public Stack GetCommandStack() 15 | { 16 | return this._commandStack; 17 | } 18 | 19 | int _capacity; 20 | 21 | public CommandStack(int commandCapacity) 22 | { 23 | this._commandStack = new Stack(); 24 | this._capacity = commandCapacity; 25 | } 26 | 27 | public boolean isFull() 28 | { 29 | return this._commandStack.size() >= this._capacity; 30 | } 31 | 32 | public boolean isEmpty() 33 | { 34 | return this._commandStack.empty(); 35 | } 36 | 37 | public boolean performCommand(Command command) 38 | { 39 | if (!this.isFull()) 40 | { 41 | this._commandStack.push(command); 42 | return true; 43 | } 44 | return false; 45 | } 46 | 47 | public boolean performCommands(List commands) 48 | { 49 | boolean inserted = true; 50 | for (Command c : commands) 51 | { 52 | inserted = this.performCommand(c); 53 | } 54 | return inserted; 55 | } 56 | 57 | public Command UndoCommand() 58 | { 59 | return this._commandStack.pop(); 60 | } 61 | 62 | public void reset() 63 | { 64 | this._commandStack.removeAllElements(); 65 | } 66 | 67 | public int totalCommands() 68 | { 69 | return this._commandStack.size(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Chapter04/Objective-C/EDSCommandStack.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSCommandStack.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/28/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSCommand; 12 | 13 | @interface EDSCommandStack() 14 | { 15 | NSMutableArray *_commandStack; 16 | NSInteger _capacity; 17 | } 18 | 19 | @property (nonatomic,readonly) NSMutableArray *commandStack; 20 | 21 | -(instancetype)initWithCommandCapacity:(NSInteger)commandCapacity 22 | { 23 | if (self = [super init]) 24 | { 25 | _commandStack = [NSMutableArray array]; 26 | _capacity = capacity; 27 | } 28 | return self; 29 | } 30 | 31 | -(BOOL)isFull 32 | { 33 | return [_commandStack count] >= _capacity; 34 | } 35 | 36 | -(BOOL)isEmpty 37 | { 38 | return [_commandStack count] == 0; 39 | } 40 | 41 | -(BOOL)performCommand:(EDSCommand*)command 42 | { 43 | if (![self isFull]) 44 | { 45 | [_commandStack addObject:command]; 46 | return YES; 47 | } 48 | return NO; 49 | } 50 | 51 | -(BOOL)performCommands:(NSArray *)commands 52 | { 53 | bool inserted = true; 54 | for (EDSCommand *c in commands) { 55 | inserted = [self performCommand:c]; 56 | } 57 | return inserted; 58 | } 59 | 60 | -(EDSCommand*)undoCommand 61 | { 62 | EDSCommand *c = [_commandStack lastObject]; 63 | [_commandStack removeLastObject]; 64 | return c; 65 | } 66 | 67 | -(void)reset 68 | { 69 | [_commandStack removeAllObjects]; 70 | } 71 | 72 | -(NSInteger)totalCommands 73 | { 74 | return [_commandStack count]; 75 | } 76 | 77 | @end 78 | -------------------------------------------------------------------------------- /Chapter04/Objective-C/EDSCommandStack.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSCommandStack.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/28/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSCommandStack.h" 10 | #import "EDSCommand.h" 11 | 12 | @interface EDSCommandStack() 13 | { 14 | NSMutableArray *_commandStack; 15 | NSInteger _capacity; 16 | } 17 | 18 | @end 19 | 20 | @implementation EDSCommandStack 21 | 22 | -(instancetype)initWithCommandCapacity:(NSInteger)commandCapacity 23 | { 24 | if (self = [super init]) 25 | { 26 | _commandStack = [NSMutableArray array]; 27 | _capacity = commandCapacity; 28 | } 29 | return self; 30 | } 31 | 32 | -(BOOL)isFull 33 | { 34 | return [_commandStack count] >= _capacity; 35 | } 36 | 37 | -(BOOL)isEmpty 38 | { 39 | return [_commandStack count] == 0; 40 | } 41 | 42 | -(BOOL)performCommand:(EDSCommand*)command 43 | { 44 | if (![self isFull]) 45 | { 46 | [_commandStack addObject:command]; 47 | return YES; 48 | } 49 | return NO; 50 | } 51 | 52 | -(BOOL)performCommands:(NSArray *)commands 53 | { 54 | bool inserted = YES; 55 | for (EDSCommand *c in commands) { 56 | inserted = [self performCommand:c]; 57 | } 58 | return inserted; 59 | } 60 | 61 | -(EDSCommand*)undoCommand 62 | { 63 | EDSCommand *c = [_commandStack lastObject]; 64 | [_commandStack removeLastObject]; 65 | return c; 66 | } 67 | 68 | -(void)reset 69 | { 70 | [_commandStack removeAllObjects]; 71 | } 72 | 73 | -(NSInteger)totalCommands 74 | { 75 | return [_commandStack count]; 76 | } 77 | 78 | @end 79 | -------------------------------------------------------------------------------- /Chapter04/Swift/CommandStack.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CommandStack.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/28/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class CommandStack 12 | { 13 | open fileprivate(set) var _commandStack: Array = [Command]() 14 | open fileprivate(set) var _capacity: Int; 15 | 16 | public init (commandCapacity: Int) 17 | { 18 | _capacity = commandCapacity 19 | } 20 | 21 | open func IsFull() -> Bool 22 | { 23 | return _commandStack.count >= _capacity 24 | } 25 | 26 | open func IsEmpty() -> Bool 27 | { 28 | return _commandStack.count == 0 29 | } 30 | 31 | open func PerformCommand(_command: Command) -> Bool 32 | { 33 | if (!IsFull()) 34 | { 35 | _commandStack.append(command) 36 | return true 37 | } 38 | return false 39 | } 40 | 41 | open func PerformCommands(_commands: [Command]) -> Bool 42 | { 43 | var inserted: Bool = true; 44 | for c in commands 45 | { 46 | inserted = PerformCommand(c) 47 | } 48 | return inserted 49 | } 50 | 51 | open func UndoCommand() -> Command 52 | { 53 | return _commandStack.popLast()! 54 | } 55 | 56 | open func Reset() 57 | { 58 | _commandStack.removeAll() 59 | } 60 | 61 | open func TotalCommands() -> Int 62 | { 63 | return _commandStack.count 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Chapter05/C#/CustomerQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class CustomerQueue 7 | { 8 | Queue _custQueue; 9 | int _cap; 10 | 11 | public CustomerQueue(int capacity) 12 | { 13 | _custQueue = new Queue(); 14 | _cap = capacity; 15 | } 16 | 17 | private bool CanCheckinCustomer() 18 | { 19 | return this._custQueue.Count < this._cap; 20 | } 21 | 22 | public void CustomerCheckin(Customer c) 23 | { 24 | if (this.CanCheckinCustomer()) 25 | { 26 | this._custQueue.Enqueue(c); 27 | } 28 | } 29 | 30 | public Customer CustomerConsultation() 31 | { 32 | return this._custQueue.Peek(); 33 | } 34 | 35 | public void CustomerCheckout() 36 | { 37 | this._custQueue.Dequeue(); 38 | } 39 | 40 | public void ClearCustomers() 41 | { 42 | this._custQueue.Clear(); 43 | } 44 | 45 | public void CustomerCancel(Customer c) 46 | { 47 | Queue tempQueue = new Queue(); 48 | foreach (Customer cust in this._custQueue) 49 | { 50 | if (cust.Equals(c)) 51 | { 52 | continue; 53 | } 54 | tempQueue.Enqueue(c); 55 | } 56 | this._custQueue = tempQueue; 57 | } 58 | 59 | public int CustomerPosition(Customer c) 60 | { 61 | if (this._custQueue.Contains(c)) 62 | { 63 | int i = 0; 64 | foreach (Customer cust in this._custQueue) 65 | { 66 | if (cust.Equals(c)) 67 | { 68 | return i; 69 | } 70 | i++; 71 | } 72 | } 73 | 74 | return -1; 75 | } 76 | 77 | public int CustomersInLine() 78 | { 79 | return this._custQueue.Count; 80 | } 81 | 82 | public bool IsLineEmpty() 83 | { 84 | return this._custQueue.Count == 0; 85 | } 86 | 87 | public bool IsLineFull() 88 | { 89 | return this._custQueue.Count == this._cap; 90 | } 91 | } 92 | } 93 | 94 | -------------------------------------------------------------------------------- /Chapter05/Java/CustomerQueue.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | /** 6 | * Created by Will Smith on 8/31/16. 7 | */ 8 | public class CustomerQueue { 9 | ArrayDeque _custQueue; 10 | int _cap; 11 | 12 | public CustomerQueue(int capacity) 13 | { 14 | _custQueue = new ArrayDeque(); 15 | _cap = capacity; 16 | } 17 | 18 | private boolean canCheckinCustomer() 19 | { 20 | return this._custQueue.size() < this._cap; 21 | } 22 | 23 | public void customerCheckin(Customer c) 24 | { 25 | if (this.canCheckinCustomer()) 26 | { 27 | this._custQueue.addLast(c); 28 | } 29 | } 30 | 31 | public Customer customerConsultation() 32 | { 33 | return this._custQueue.peek(); 34 | } 35 | 36 | public void customerCheckout() 37 | { 38 | this._custQueue.removeFirst(); 39 | } 40 | 41 | public void clearCustomers() 42 | { 43 | this._custQueue.clear(); 44 | } 45 | 46 | public void customerCancel(Customer c) 47 | { 48 | this._custQueue.remove(c); 49 | } 50 | 51 | public int customerPosition(Customer c) 52 | { 53 | if (this._custQueue.contains(c)) 54 | { 55 | int i = 0; 56 | for (Customer cust : this._custQueue) 57 | { 58 | if (cust.equals(c)) 59 | { 60 | return i; 61 | } 62 | i++; 63 | } 64 | } 65 | 66 | return -1; 67 | } 68 | 69 | public int customersInLine() 70 | { 71 | return this._custQueue.size(); 72 | } 73 | 74 | public boolean isLineEmpty() 75 | { 76 | return this._custQueue.size() == 0; 77 | } 78 | 79 | public boolean isLineFull() 80 | { 81 | return this._custQueue.size() == this._cap; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Chapter05/Objective-C/EDSCustomerQueue.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSCustomerQueue.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/31/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSCustomer; 12 | 13 | NSMutableArray *_custQueue; 14 | int _cap; 15 | 16 | -(instancetype)initWithCapacity:(int)capacity 17 | { 18 | if (self = [super init]) 19 | { 20 | _custQueue = [NSMutableArray array]; 21 | _cap = capacity; 22 | } 23 | return self; 24 | } 25 | 26 | -(BOOL)canCheckinCustomer 27 | { 28 | return [_custQueue count] < _cap; 29 | } 30 | 31 | -(void)checkInCustomer:(EDSCustomer*)c 32 | { 33 | if ([self canCheckinCustomer]) 34 | { 35 | [_custQueue addObject:c]; 36 | } 37 | } 38 | 39 | -(EDSCustomer*)customerConsultation 40 | { 41 | return [_custQueue firstObject]; 42 | } 43 | 44 | -(void)checkoutCustomer 45 | { 46 | [_custQueue removeObjectAtIndex:0]; 47 | } 48 | 49 | -(NSUInteger)positionOfCustomer:(EDSCustomer*)c 50 | { 51 | return [_custQueue indexOfObject:c]; 52 | } 53 | 54 | -(void)clearCustomers 55 | { 56 | [_custQueue removeAllObjects]; 57 | } 58 | 59 | -(void)cancelCustomer:(EDSCustomer*)c 60 | { 61 | NSUInteger index = [self positionOfCustomer:c]; 62 | if (index != -1) 63 | { 64 | [_custQueue removeObjectAtIndex:index]; 65 | } 66 | } 67 | 68 | -(NSUInteger)customersInLine 69 | { 70 | return [_custQueue count]; 71 | } 72 | 73 | -(BOOL)isLineEmpty 74 | { 75 | return [_custQueue count] == 0; 76 | } 77 | 78 | -(BOOL)isLineFull 79 | { 80 | return [_custQueue count] == _cap; 81 | } 82 | 83 | @end 84 | -------------------------------------------------------------------------------- /Chapter05/Objective-C/EDSCustomerQueue.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSCustomerQueue.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/31/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSCustomerQueue.h" 10 | #import "EDSCustomer.h" 11 | 12 | @interface EDSCustomerQueue() 13 | { 14 | NSMutableArray *_custQueue; 15 | int _cap; 16 | } 17 | 18 | @end 19 | 20 | @implementation EDSCustomerQueue 21 | 22 | -(instancetype)initWithCapacity:(int)capacity 23 | { 24 | if (self = [super init]) 25 | { 26 | _custQueue = [NSMutableArray array]; 27 | _cap = capacity; 28 | } 29 | return self; 30 | } 31 | 32 | -(BOOL)canCheckinCustomer 33 | { 34 | return [_custQueue count] < _cap; 35 | } 36 | 37 | -(void)checkInCustomer:(EDSCustomer*)c 38 | { 39 | if ([self canCheckinCustomer]) 40 | { 41 | [_custQueue addObject:c]; 42 | } 43 | } 44 | 45 | -(EDSCustomer*)customerConsultation 46 | { 47 | return [_custQueue firstObject]; 48 | } 49 | 50 | -(void)checkoutCustomer 51 | { 52 | [_custQueue removeObjectAtIndex:0]; 53 | } 54 | 55 | -(void)clearCustomers 56 | { 57 | [_custQueue removeAllObjects]; 58 | } 59 | 60 | -(void)cancelCustomer:(EDSCustomer*)c 61 | { 62 | NSUInteger index = [self positionOfCustomer:c]; 63 | if (index != -1) 64 | { 65 | [_custQueue removeObjectAtIndex:index]; 66 | } 67 | } 68 | 69 | -(NSUInteger)positionOfCustomer:(EDSCustomer*)c 70 | { 71 | return [_custQueue indexOfObject:c]; 72 | } 73 | 74 | -(NSUInteger)customersInLine 75 | { 76 | return [_custQueue count]; 77 | } 78 | 79 | -(BOOL)isLineEmpty 80 | { 81 | return [_custQueue count] == 0; 82 | } 83 | 84 | -(BOOL)isLineFull 85 | { 86 | return [_custQueue count] == _cap; 87 | } 88 | 89 | @end 90 | -------------------------------------------------------------------------------- /Chapter05/Swift/CustomerQueue.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CustomerQueue.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/31/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class CustomerQueue 12 | { 13 | var _custQueue: Array = [Customer]() 14 | var _cap: Int; 15 | 16 | public init(capacity: Int) 17 | { 18 | _cap = capacity 19 | } 20 | 21 | open func canCheckinCustomer() -> Bool 22 | { 23 | return _custQueue.count < _cap 24 | } 25 | 26 | open func checkInCustomer(_ c: Customer) 27 | { 28 | if canCheckinCustomer() 29 | { 30 | _custQueue.append(c) 31 | } 32 | } 33 | 34 | open func customerConsultation() -> Customer 35 | { 36 | return _custQueue.first! 37 | } 38 | 39 | open func checkoutCustomer() 40 | { 41 | _custQueue.removeFirst() 42 | } 43 | 44 | open func clearCustomers() 45 | { 46 | _custQueue.removeAll() 47 | } 48 | 49 | open func cancelCustomer(_ c: Customer) 50 | { 51 | if let index = _custQueue.index(of: c) 52 | { 53 | _custQueue.remove(at: index) 54 | } 55 | } 56 | 57 | open func positionOfCustomer(_ c: Customer) -> Int 58 | { 59 | return _custQueue.index(of: c)! 60 | } 61 | 62 | open func customersInLine() -> Int 63 | { 64 | return _custQueue.count 65 | } 66 | 67 | open func isLineEmpty() -> Bool 68 | { 69 | return _custQueue.count == 0 70 | } 71 | 72 | open func isLineFull() -> Bool 73 | { 74 | return _custQueue.count == _cap 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Chapter06/C#/PointsDictionary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class PointsDictionary 7 | { 8 | Dictionary _points; 9 | 10 | public PointsDictionary() 11 | { 12 | _points = new Dictionary(); 13 | } 14 | 15 | //This method accepts negative values 16 | private int UpdateCustomerPoints(string customerName, int points) 17 | { 18 | if (this.CustomerExists(customerName)) 19 | { 20 | _points[customerName] = _points[customerName] += points; 21 | return _points[customerName]; 22 | } 23 | return 0; 24 | } 25 | 26 | //Add 27 | public void RegisterCustomer(string customerName) 28 | { 29 | this.RegisterCustomer(customerName, 0); 30 | } 31 | 32 | public void RegisterCustomer(string customerName, int previousBalance) 33 | { 34 | _points.Add(customerName, previousBalance); 35 | } 36 | 37 | //Get 38 | //We use this method because it uses TryGetValue to avoid exceptions 39 | public int GetCustomerPoints(string customerName) 40 | { 41 | int points; 42 | //This returns bool if for whetehr it finds the key 43 | //if it does find it, it sets the out property 44 | //We don't care about the bool value, just the points 45 | //Our customers eithe rhave points or not 46 | _points.TryGetValue(customerName, out points); 47 | 48 | return points; 49 | } 50 | 51 | //Update 52 | public int AddCustomerPoints(string customerName, int points) 53 | { 54 | return this.UpdateCustomerPoints(customerName, points); 55 | } 56 | 57 | public int RemoveCustomerPoints(string customerName, int points) 58 | { 59 | return this.UpdateCustomerPoints(customerName, -points); 60 | } 61 | 62 | public int RedeemCustomerPoints(string customerName, int points) 63 | { 64 | return this.UpdateCustomerPoints(customerName, -points); 65 | } 66 | 67 | //Remove 68 | public int CustomerCheckout(string customerName) 69 | { 70 | int points = this.GetCustomerPoints(customerName); 71 | _points.Remove(customerName); 72 | return points; 73 | } 74 | 75 | //Contains 76 | public bool CustomerExists(string customerName) 77 | { 78 | return _points.ContainsKey(customerName); 79 | } 80 | 81 | //Count 82 | public int CustomersOnPremises() 83 | { 84 | return _points.Count; 85 | } 86 | 87 | //Clear 88 | public void ClosingTime() 89 | { 90 | //Perform accounting actions 91 | _points.Clear(); 92 | } 93 | } 94 | } 95 | 96 | -------------------------------------------------------------------------------- /Chapter06/Java/PointsDictionary.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Created by William Smith on 9/7/16. 7 | */ 8 | public class PointsDictionary { 9 | HashMap _points; 10 | 11 | public PointsDictionary() 12 | { 13 | _points = new HashMap<>(); 14 | } 15 | 16 | //This method accepts negative values 17 | private Integer UpdateCustomerPoints(String customerName, int points) 18 | { 19 | if (this.CustomerExists(customerName)) 20 | { 21 | _points.put(customerName, _points.get(customerName) + points); 22 | return _points.get(customerName); 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | //Add 29 | public void RegisterCustomer(String customerName) 30 | { 31 | this.RegisterCustomer(customerName, 0); 32 | } 33 | 34 | public void RegisterCustomer(String customerName, int previousBalance) 35 | { 36 | _points.put(customerName, previousBalance); 37 | } 38 | 39 | //Get 40 | public Integer GetCustomerPoints(String customerName) 41 | { 42 | return _points.get(customerName) == null ? 0 : _points.get(customerName); 43 | } 44 | 45 | //Update 46 | public Integer AddCustomerPoints(String customerName, int points) 47 | { 48 | return this.UpdateCustomerPoints(customerName, points); 49 | } 50 | 51 | public Integer RemoveCustomerPoints(String customerName, int points) 52 | { 53 | return this.UpdateCustomerPoints(customerName, -points); 54 | } 55 | 56 | public Integer RedeemCustomerPoints(String customerName, int points) 57 | { 58 | return this.UpdateCustomerPoints(customerName, -points); 59 | } 60 | 61 | //Remove 62 | public Integer CustomerCheckout(String customerName) 63 | { 64 | Integer points = this.GetCustomerPoints(customerName); 65 | _points.remove(customerName); 66 | return points; 67 | } 68 | 69 | //Contains 70 | public boolean CustomerExists(String customerName) 71 | { 72 | return _points.containsKey(customerName); 73 | } 74 | 75 | //Count 76 | public int CustomersOnPremises() 77 | { 78 | return _points.size(); 79 | } 80 | 81 | //Clear 82 | public void ClosingTime() 83 | { 84 | //Perform accounting actions 85 | _points.clear(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Chapter06/Objective-C/EDSPointsDictionary.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSPointsDictionary.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/7/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSPointsDictionary : NSObject 12 | -(void)registerCustomer:(NSString*)customerName; 13 | 14 | -(void)registerCustomer:(NSString*)customerName 15 | withPreviousBalance:(NSInteger)previousBalance; 16 | 17 | -(NSInteger)getCustomerPoints:(NSString*)customerName; 18 | 19 | -(NSInteger)addPoints:(NSInteger)points 20 | toCustomer:(NSString*)customerName; 21 | 22 | -(NSInteger)removePoints:(NSInteger)points 23 | fromCustomer:(NSString*)customerName; 24 | 25 | -(NSInteger)redeemPoints:(NSInteger)points 26 | forCustomer:(NSString*)customerName; 27 | 28 | -(NSInteger)customerCheckout:(NSString*)customerName; 29 | 30 | -(bool)customerExists:(NSString*)customerName; 31 | 32 | -(NSInteger)customersOnPremises; 33 | 34 | -(void)closingTime; 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /Chapter06/Objective-C/EDSPointsDictionary.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSPointsDictionary.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/7/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSPointsDictionary.h" 10 | 11 | @interface EDSPointsDictionary() 12 | { 13 | NSMutableDictionary *_points; 14 | } 15 | 16 | @end 17 | 18 | @implementation EDSPointsDictionary 19 | 20 | -(instancetype)init 21 | { 22 | if (self = [super init]) 23 | { 24 | _points = [NSMutableDictionary dictionary]; 25 | } 26 | 27 | return self; 28 | } 29 | 30 | -(NSInteger)updatePoints:(NSInteger)points 31 | forCustomer:(NSString*)customerName 32 | { 33 | if ([self customerExists:customerName]) 34 | { 35 | NSInteger exPoints = [[_points objectForKey:customerName] integerValue]; 36 | exPoints += points; 37 | 38 | [_points setValue:[NSNumber numberWithInteger:exPoints] forKey:customerName]; 39 | return [[_points objectForKey:customerName] integerValue]; 40 | } 41 | return 0; 42 | } 43 | 44 | //Add 45 | -(void)registerCustomer:(NSString*)customerName 46 | { 47 | [self registerCustomer:customerName withPreviousBalance:0]; 48 | } 49 | 50 | -(void)registerCustomer:(NSString*)customerName 51 | withPreviousBalance:(NSInteger)previousBalance 52 | { 53 | NSNumber *points = [NSNumber numberWithInteger:previousBalance]; 54 | [_points setObject:points forKey:customerName]; 55 | } 56 | 57 | //Get 58 | -(NSInteger)getCustomerPoints:(NSString*)customerName 59 | { 60 | NSNumber *rawsPoints = [_points objectForKey:customerName]; 61 | return rawsPoints ? [rawsPoints integerValue] : 0; 62 | } 63 | 64 | //Update 65 | -(NSInteger)addPoints:(NSInteger)points 66 | toCustomer:(NSString*)customerName 67 | { 68 | return [self updatePoints:points forCustomer:customerName]; 69 | } 70 | 71 | -(NSInteger)removePoints:(NSInteger)points 72 | fromCustomer:(NSString*)customerName 73 | { 74 | return [self updatePoints:-points forCustomer:customerName]; 75 | } 76 | 77 | -(NSInteger)redeemPoints:(NSInteger)points 78 | forCustomer:(NSString*)customerName 79 | { 80 | return [self updatePoints:-points forCustomer:customerName]; 81 | } 82 | 83 | -(NSInteger)customerCheckout:(NSString*)customerName 84 | { 85 | NSInteger points = [[_points objectForKey:customerName] integerValue]; 86 | [_points removeObjectForKey:customerName]; 87 | return points; 88 | } 89 | 90 | //Contains 91 | -(bool)customerExists:(NSString*)customerName 92 | { 93 | //Returns nil if no key, which reads as false. 94 | //Cannot add nil to a dictionary so this is type safe also 95 | return [_points objectForKey:customerName]; 96 | } 97 | 98 | //Count 99 | -(NSInteger)customersOnPremises 100 | { 101 | return [_points count]; 102 | } 103 | 104 | //Clear 105 | -(void)closingTime 106 | { 107 | [_points removeAllObjects]; 108 | } 109 | 110 | @end 111 | -------------------------------------------------------------------------------- /Chapter06/Swift/PointsDictionary.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PointsDictionary.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 9/7/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class PointsDictionary 12 | { 13 | var _points = Dictionary() 14 | 15 | open func updatePointsForCustomer(_ points: Int, customerName: String) -> Int 16 | { 17 | if customerExists(customerName) 18 | { 19 | _points[customerName] = _points[customerName]! + points 20 | return _points[customerName]! 21 | } 22 | return 0 23 | } 24 | 25 | //Add 26 | open func registerCustomer(_ customerName: String) 27 | { 28 | registerCustomerWithPreviousBalance(customerName, previousBalance: 0) 29 | } 30 | 31 | open func registerCustomerWithPreviousBalance(_ customerName: String, previousBalance: Int) 32 | { 33 | _points[customerName] = previousBalance; 34 | } 35 | 36 | //Get 37 | open func getCustomerPoints(_ customerName: String) -> Int 38 | { 39 | let rawsPoints = _points[customerName] 40 | return rawsPoints != nil ? rawsPoints! : 0; 41 | } 42 | 43 | //Update 44 | open func addPointsToCustomer(_ points: Int, customerName: String) -> Int 45 | { 46 | return updatePointsForCustomer(points, customerName: customerName) 47 | } 48 | 49 | open func removePointsFromCustomer(_ points: Int, customerName: String) -> Int 50 | { 51 | return updatePointsForCustomer(-points, customerName: customerName) 52 | } 53 | 54 | open func redeemPointsForCustomer(_ points: Int, customerName: String) -> Int 55 | { 56 | return updatePointsForCustomer(-points, customerName: customerName) 57 | } 58 | 59 | open func customerCheckout(_ customerName: String) -> Int 60 | { 61 | let points = _points[customerName] 62 | _points.removeValue(forKey: customerName) 63 | return points!; 64 | } 65 | 66 | //Contains 67 | open func customerExists(_ customerName: String) -> Bool 68 | { 69 | //Returns nil if no key, which reads as false. 70 | //Cannot add nil to a dictionary so this is type safe also 71 | return _points[customerName] != nil 72 | } 73 | 74 | //Count 75 | open func customersOnPremises() -> Int 76 | { 77 | return _points.count 78 | } 79 | 80 | //Clear 81 | open func closingTime() 82 | { 83 | _points.removeAll() 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Chapter07/C#/LoggedInUserSet.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class LoggedInUserSet 7 | { 8 | HashSet _users; 9 | 10 | public LoggedInUserSet() 11 | { 12 | _users = new HashSet(); 13 | } 14 | 15 | public bool UserAuthenticated(User user) 16 | { 17 | if (_users.Count < 30) 18 | { 19 | return _users.Add(user); 20 | } 21 | return false; 22 | } 23 | 24 | public void UserLoggedOut(User user) 25 | { 26 | _users.Remove(user); 27 | } 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Chapter07/C#/PlaylistSet.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class PlaylistSet 7 | { 8 | HashSet _songs; 9 | 10 | public Int16 capacity { get; private set; } 11 | public bool premiumUser { get; private set; } 12 | public bool isEmpty 13 | { 14 | get 15 | { 16 | return _songs.Count == 0; 17 | } 18 | } 19 | 20 | public bool isFull 21 | { 22 | get 23 | { 24 | if (this.premiumUser == true) 25 | { 26 | return false; 27 | } 28 | else 29 | { 30 | return _songs.Count == this.capacity; 31 | } 32 | } 33 | } 34 | 35 | public PlaylistSet(bool premiumUser, Int16 capacity) 36 | { 37 | _songs = new HashSet(); 38 | this.premiumUser = premiumUser; 39 | this.capacity = capacity; 40 | } 41 | 42 | public bool AddSong(Song song) 43 | { 44 | if (!this.isFull) 45 | { 46 | return _songs.Add(song); 47 | } 48 | return false; 49 | } 50 | 51 | public bool RemoveSong(Song song) 52 | { 53 | return _songs.Remove(song); 54 | } 55 | 56 | public void MergeWithPlaylist(HashSet playlist) 57 | { 58 | _songs.UnionWith(playlist); 59 | } 60 | 61 | public HashSet FindSharedSongsInPlaylist(HashSet playlist) 62 | { 63 | HashSet songsCopy = new HashSet(_songs); 64 | songsCopy.IntersectWith(playlist); 65 | return songsCopy; 66 | } 67 | 68 | public HashSet FindUniqueSongs(HashSet playlist) 69 | { 70 | HashSet songsCopy = new HashSet(_songs); 71 | songsCopy.ExceptWith(playlist); 72 | return songsCopy; 73 | } 74 | 75 | public bool IsSubset(HashSet playlist) 76 | { 77 | return _songs.IsSubsetOf(playlist); 78 | } 79 | 80 | public bool IsSuperset(HashSet playlist) 81 | { 82 | return _songs.IsSupersetOf(playlist); 83 | } 84 | 85 | public int TotalSongs() 86 | { 87 | return _songs.Count; 88 | } 89 | } 90 | } 91 | 92 | -------------------------------------------------------------------------------- /Chapter07/Java/LoggedInUserSet.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Created by William Smith on 9/11/16. 7 | */ 8 | public class LoggedInUserSet { 9 | HashSet _users; 10 | 11 | public LoggedInUserSet() 12 | { 13 | _users = new HashSet(); 14 | } 15 | 16 | public boolean userAuthenticated(User user) 17 | { 18 | if (_users.size() < 30) 19 | { 20 | return _users.add(user); 21 | } 22 | return false; 23 | } 24 | 25 | public void userLoggedOut(User user) 26 | { 27 | _users.remove(user); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter07/Java/PlaylistSet.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Created by William Smith on 9/12/16. 7 | */ 8 | public class PlaylistSet { 9 | 10 | HashSet _songs; 11 | 12 | public int capacity; 13 | public boolean premiumUser; 14 | public boolean isEmpty() 15 | { 16 | return _songs.size() == 0; 17 | } 18 | 19 | public boolean isFull() 20 | { 21 | if (this.premiumUser == true) 22 | { 23 | return false; 24 | } 25 | else { 26 | return _songs.size() == this.capacity; 27 | } 28 | } 29 | 30 | public PlaylistSet(boolean premiumUser, int capacity) 31 | { 32 | _songs = new HashSet<>(); 33 | this.premiumUser = premiumUser; 34 | this.capacity = capacity; 35 | } 36 | 37 | public boolean addSong(Song song) 38 | { 39 | if (!this.isFull()) 40 | { 41 | return _songs.add(song); 42 | } 43 | return false; 44 | } 45 | 46 | public boolean removeSong(Song song) 47 | { 48 | return _songs.remove(song); 49 | } 50 | 51 | public void mergeWithPlaylist(HashSet playlist) 52 | { 53 | _songs.addAll(playlist); 54 | } 55 | 56 | public HashSet findSharedSongsInPlaylist(HashSet playlist) 57 | { 58 | HashSet songsCopy = new HashSet<>(_songs); 59 | songsCopy.retainAll(playlist); 60 | return songsCopy; 61 | } 62 | 63 | public HashSet findUniqueSongs(HashSet playlist) 64 | { 65 | HashSet songsCopy = new HashSet<>(_songs); 66 | songsCopy.removeAll(playlist); 67 | return songsCopy; 68 | } 69 | 70 | public boolean isSubset(HashSet playlist) 71 | { 72 | return _songs.containsAll(playlist); 73 | } 74 | 75 | public boolean isSuperset(HashSet playlist) 76 | { 77 | return playlist.containsAll(_songs); 78 | } 79 | 80 | public int totalSongs() 81 | { 82 | return _songs.size(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Chapter07/Objective-C/EDSLoggedInUserSet.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSLoggedInUserSet.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSUser; 12 | 13 | @interface EDSLoggedInUserSet : NSObject 14 | 15 | -(void)userAuthenticated:(EDSUser*)user; 16 | 17 | -(void)userLoggedOut:(EDSUser*)user; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /Chapter07/Objective-C/EDSLoggedInUserSet.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSLoggedInUserSet.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSLoggedInUserSet.h" 10 | #import "EDSUser.h" 11 | 12 | @interface EDSLoggedInUserSet() 13 | { 14 | NSMutableSet *_users; 15 | } 16 | 17 | @end 18 | 19 | @implementation EDSLoggedInUserSet 20 | 21 | -(instancetype)init 22 | { 23 | if (self = [super init]) 24 | { 25 | _users = [NSMutableSet set]; 26 | } 27 | 28 | return self; 29 | } 30 | 31 | -(void)userAuthenticated:(EDSUser *)user 32 | { 33 | if ([_users count] < 30) 34 | { 35 | [_users addObject:user]; 36 | } 37 | } 38 | 39 | -(void)userLoggedOut:(EDSUser *)user 40 | { 41 | [_users removeObject:user]; 42 | } 43 | 44 | @end 45 | -------------------------------------------------------------------------------- /Chapter07/Objective-C/EDSPlaylistSet.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSPlaylistSet.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/12/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSSong; 12 | 13 | @interface EDSPlaylistSet : NSObject 14 | 15 | @property (readonly) BOOL premiumUser; 16 | @property (readonly) BOOL isEmpty; 17 | @property (readonly) BOOL isFull; 18 | 19 | -(instancetype)playlistSetWithPremiumUser:(BOOL)isPremiumUser 20 | andCapacity:(NSInteger)capacity; 21 | 22 | -(BOOL)addSong:(EDSSong*)song; 23 | -(BOOL)removeSong:(EDSSong*)song; 24 | -(void)mergeWithPlaylist:(NSMutableSet*)playlist; 25 | -(NSMutableSet*)findSharedSongsInPlaylist:(NSMutableSet*)playlist; 26 | -(NSMutableSet*)findUniqueSongs:(NSMutableSet*)playlist; 27 | -(BOOL)isSubset:(NSMutableSet*)playlist; 28 | -(BOOL)isSuperset:(NSMutableSet*)playlist; 29 | -(NSInteger)totalSongs; 30 | 31 | @end 32 | -------------------------------------------------------------------------------- /Chapter07/Objective-C/EDSPlaylistSet.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSPlaylistSet.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/12/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSPlaylistSet.h" 10 | #import "EDSSong.h" 11 | 12 | @interface EDSPlaylistSet() 13 | { 14 | NSMutableSet* _songs; 15 | NSInteger _capacity; 16 | BOOL _premiumUser; 17 | BOOL _isEmpty; 18 | BOOL _isFull; 19 | } 20 | @end 21 | 22 | @implementation EDSPlaylistSet 23 | 24 | -(instancetype)playlistSetWithPremiumUser:(BOOL)isPremiumUser 25 | andCapacity:(NSInteger)capacity 26 | { 27 | if (self == [super init]) 28 | { 29 | _songs = [NSMutableSet set]; 30 | _premiumUser = isPremiumUser; 31 | _capacity = capacity; 32 | 33 | CGPoint p = CGPointMake(9.0, 5.2); 34 | p.x = 9.8; 35 | p.y = 5.5; 36 | } 37 | return self; 38 | } 39 | 40 | -(BOOL)isEmpty 41 | { 42 | return [_songs count] == 0; 43 | } 44 | 45 | -(BOOL)isFull 46 | { 47 | if (_premiumUser) 48 | { 49 | return NO; 50 | } 51 | else 52 | { 53 | return [_songs count] == _capacity; 54 | } 55 | } 56 | 57 | -(BOOL)addSong:(EDSSong*)song 58 | { 59 | if (!_isFull && ![_songs containsObject:song]) 60 | { 61 | [_songs addObject:song]; 62 | return YES; 63 | } 64 | return NO; 65 | } 66 | 67 | -(BOOL)removeSong:(EDSSong*)song 68 | { 69 | if ([_songs containsObject:song]) 70 | { 71 | [_songs removeObject:song]; 72 | return YES; 73 | 74 | } 75 | else 76 | { 77 | return NO; 78 | } 79 | } 80 | 81 | -(void)mergeWithPlaylist:(NSMutableSet*)playlist 82 | { 83 | [_songs unionSet:playlist]; 84 | } 85 | 86 | -(NSMutableSet*)findSharedSongsInPlaylist:(NSMutableSet*)playlist 87 | { 88 | NSMutableSet *songsCopy = [NSMutableSet setWithSet:_songs]; 89 | [songsCopy intersectSet:playlist]; 90 | return songsCopy; 91 | } 92 | 93 | -(NSMutableSet*)findUniqueSongs:(NSMutableSet*)playlist 94 | { 95 | NSMutableSet *songsCopy = [NSMutableSet setWithSet:_songs]; 96 | [songsCopy minusSet:playlist]; 97 | return songsCopy; 98 | } 99 | 100 | -(BOOL)isSubset:(NSMutableSet*)playlist 101 | { 102 | return [_songs isSubsetOfSet:playlist]; 103 | } 104 | 105 | -(BOOL)isSuperset:(NSMutableSet*)playlist 106 | { 107 | return [playlist isSubsetOfSet:_songs]; 108 | } 109 | 110 | -(NSInteger)totalSongs 111 | { 112 | return [_songs count]; 113 | } 114 | 115 | @end 116 | -------------------------------------------------------------------------------- /Chapter07/Swift/LoggedInUserSet.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LoggedInUserSet.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 9/11/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | open class LoggedInUserSet 12 | { 13 | var _users: Set = Set() 14 | 15 | open func userAuthenticated(_ user: User) 16 | { 17 | if (_users.count < 30) 18 | { 19 | _users.insert(user) 20 | } 21 | } 22 | 23 | open func userLoggedOut(_ user: User) 24 | { 25 | if let index = _users.index(of: user) 26 | { 27 | _users.remove(at: index) 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter07/Swift/PlaylistSet.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PlaylistSet.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 9/12/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public struct RGBAColor { 12 | var red = 0 13 | var green = 0 14 | var blue = 0 15 | var alpha = 0.0 16 | 17 | public init(R: Int, G: Int, B: Int, A: Double) 18 | { 19 | red = R 20 | green = G 21 | blue = B 22 | alpha = A 23 | } 24 | } 25 | 26 | open class PlaylistSet 27 | { 28 | var _songs: Set = Set() 29 | open fileprivate(set) var _capacity: Int 30 | open fileprivate(set) var _premiumUser: Bool 31 | open fileprivate(set) var _isEmpty: Bool 32 | open fileprivate(set) var _isFull: Bool 33 | 34 | public init (capacity: Int, premiumUser: Bool) 35 | { 36 | let color = RGBAColor(R: 139, G:0, B:139, A:0.5) 37 | 38 | _capacity = capacity 39 | _premiumUser = premiumUser 40 | _isEmpty = true 41 | _isFull = false 42 | } 43 | 44 | open func premiumUser() -> Bool 45 | { 46 | return _premiumUser 47 | } 48 | 49 | open func isEmpty() -> Bool 50 | { 51 | return _songs.count == 0 52 | } 53 | 54 | open func isFull() -> Bool 55 | { 56 | if (_premiumUser) 57 | { 58 | return false 59 | } 60 | else 61 | { 62 | return _songs.count == _capacity 63 | } 64 | } 65 | 66 | open func addSong(_ song: Song) -> Bool 67 | { 68 | if (!_isFull && !_songs.contains(song)) 69 | { 70 | _songs.insert(song) 71 | return true 72 | } 73 | return false 74 | } 75 | 76 | open func removeSong(_ song: Song) -> Bool 77 | { 78 | if (_songs.contains(song)) 79 | { 80 | _songs.remove(song) 81 | return true 82 | } 83 | else 84 | { 85 | return false 86 | } 87 | } 88 | 89 | open func mergeWithPlaylist(_ playlist: Set) 90 | { 91 | _songs.formUnion(playlist) 92 | } 93 | 94 | open func findSharedSongsInPlaylist(_ playlist: Set) -> Set 95 | { 96 | return _songs.intersection(playlist) 97 | } 98 | 99 | open func findUniqueSongs(_ playlist: Set) -> Set 100 | { 101 | return _songs.subtracting(playlist) 102 | } 103 | 104 | open func isSubset(_ playlist: Set) -> Bool 105 | { 106 | return _songs.isSubset(of: playlist) 107 | } 108 | 109 | open func isSuperset(_ playlist: Set) -> Bool 110 | { 111 | return _songs.isSuperset(of: playlist) 112 | } 113 | 114 | open func totalSongs() -> Int 115 | { 116 | return _songs.count; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Chapter08/C#/SilverLine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace EverydayDataStructures 3 | { 4 | public enum SilverLineEnum 5 | { 6 | Wiehle_Reston_East = 90, 7 | Spring_Hill = 100, 8 | Greensboro = 200, 9 | Tysons_Corner = 300, 10 | McClean = 400, 11 | East_Falls_Church = 500, 12 | Ballston_MU = 600, 13 | Virginia_Sq_GMU = 700, 14 | Clarendon = 800, 15 | Courthouse = 900, 16 | Rosslyn = 1000, 17 | Foggy_Bottom_GWU = 1100, 18 | Farragut_West = 1200, 19 | McPherson_Sq = 1300, 20 | Metro_Center = 2000, 21 | Federal_Triangle = 2100, 22 | Smithsonian = 2200, 23 | LEnfant_Plaza = 4000, 24 | Federal_Center_SW = 4100, 25 | Capital_South = 4200, 26 | Eastern_Market = 4300, 27 | Potomac_Ave = 4400, 28 | Stadium_Armory = 5000, 29 | Benning_Road = 5100, 30 | Capital_Heights = 5200, 31 | Addison_Road = 5300, 32 | Morgan_Blvd = 5400, 33 | Largo_Town_Center = 5500 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Chapter08/C#/WaypointList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class WaypointList 7 | { 8 | LinkedList route; 9 | LinkedListNode current; 10 | 11 | public WaypointList() 12 | { 13 | this.route = new LinkedList(); 14 | } 15 | 16 | public void AddWaypoints(List waypoints) 17 | { 18 | foreach (Waypoint w in waypoints) 19 | { 20 | this.route.AddLast(w); 21 | } 22 | } 23 | 24 | public bool RemoveWaypoint(Waypoint waypoint) 25 | { 26 | return this.route.Remove(waypoint); 27 | } 28 | 29 | public void InsertWaypointsBefore(List waypoints, Waypoint before) 30 | { 31 | LinkedListNode node = this.route.Find(before); 32 | if (node != null) 33 | { 34 | foreach (Waypoint w in waypoints) 35 | { 36 | this.route.AddBefore(node, w); 37 | } 38 | } 39 | else 40 | { 41 | this.AddWaypoints(waypoints); 42 | } 43 | } 44 | 45 | public bool StartRoute() 46 | { 47 | if (this.route.Count > 1) 48 | { 49 | this.current = this.StartingLine(); 50 | return this.MoveToNextWaypoint(); 51 | } 52 | return false; 53 | } 54 | 55 | public bool MoveToNextWaypoint() 56 | { 57 | if (this.current != null) 58 | { 59 | this.current.Value.DeactivateWaypoint(); 60 | if (this.current != this.FinishLine()) 61 | { 62 | this.current = this.current.Next; 63 | return true; 64 | } 65 | return false; 66 | } 67 | return false; 68 | } 69 | 70 | public bool MoveToPreviousWaypoint() 71 | { 72 | if (this.current != null && 73 | this.current != this.StartingLine()) 74 | { 75 | this.current = this.current.Previous; 76 | this.current.Value.ReactivateWaypoint(); 77 | return true; 78 | } 79 | return false; 80 | } 81 | 82 | public LinkedListNode StartingLine() 83 | { 84 | return this.route.First; 85 | } 86 | 87 | public LinkedListNode FinishLine() 88 | { 89 | return this.route.Last; 90 | } 91 | 92 | public LinkedListNode CurrentWaypoint() 93 | { 94 | return this.current; 95 | } 96 | } 97 | } 98 | 99 | -------------------------------------------------------------------------------- /Chapter08/Java/SilverLine.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /** 4 | * Created by William Smith on 9/19/16. 5 | */ 6 | 7 | public enum SilverLine { 8 | Wiehle_Reston_East, 9 | Spring_Hill, 10 | Greensboro, 11 | Tysons_Corner, 12 | McClean, 13 | East_Falls_Church, 14 | Ballston_MU, 15 | Virginia_Sq_GMU, 16 | Clarendon, 17 | Courthouse, 18 | Rosslyn, 19 | Foggy_Bottom_GWU, 20 | Farragut_West, 21 | McPherson_Sq, 22 | Metro_Center, 23 | Federal_Triangle, 24 | Smithsonian, 25 | LEnfant_Plaza, 26 | Federal_Center_SW, 27 | Capital_South, 28 | Eastern_Market, 29 | Potomac_Ave, 30 | Stadium_Armory, 31 | Benning_Road, 32 | Capital_Heights, 33 | Addison_Road, 34 | Morgan_Blvd, 35 | Largo_Town_Center; 36 | 37 | public static int intValue() { 38 | //Map the string to an int 39 | return 0; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Chapter08/Java/Waypoint.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /** 4 | * Created by William Smith on 8/25/16. 5 | */ 6 | public class Waypoint { 7 | 8 | int lat; 9 | int lon; 10 | boolean active; 11 | 12 | public Waypoint(int latitude, int longitude) 13 | { 14 | this.lat = latitude; 15 | this.lon = longitude; 16 | this.active = true; 17 | } 18 | 19 | public boolean getActive() 20 | { 21 | return this.active; 22 | } 23 | 24 | public void DeactivateWaypoint() 25 | { 26 | this.active = false; 27 | } 28 | 29 | public void ReactivateWaypoint() 30 | { 31 | this.active = true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter08/Objective-C/EDSWaypoint.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSWaypoint.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/24/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSWaypoint : NSObject 12 | 13 | //Is the waypoint currently active 14 | // 15 | @property (nonatomic, readonly) BOOL active; 16 | 17 | 18 | //Default initializer 19 | //Wypoints are initialized in the active state. 20 | // 21 | -(instancetype)initWithLatitude:(NSInteger)latitude 22 | andLongitude:(NSInteger)longitude; 23 | 24 | -(void)reactivateWaypoint; 25 | -(void)deactivateWaypoint; 26 | 27 | @end 28 | -------------------------------------------------------------------------------- /Chapter08/Objective-C/EDSWaypoint.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSWaypoint.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/24/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSWaypoint.h" 10 | 11 | @interface EDSWaypoint() 12 | { 13 | NSInteger _lat; 14 | NSInteger _lon; 15 | BOOL _active; 16 | } 17 | 18 | @end 19 | 20 | @implementation EDSWaypoint 21 | 22 | 23 | -(instancetype)initWithLatitude:(NSInteger)latitude 24 | andLongitude:(NSInteger)longitude 25 | { 26 | if (self = [super init]) 27 | { 28 | _lat = latitude; 29 | _lon = longitude; 30 | _active = YES; 31 | } 32 | 33 | return self; 34 | } 35 | 36 | //Header file declation for the active property: 37 | //@property (nonatomic, readonly) BOOL active; 38 | -(BOOL)active 39 | { 40 | return _active; 41 | } 42 | 43 | 44 | -(void)reactivateWaypoint 45 | { 46 | _active = YES; 47 | } 48 | 49 | -(void)deactivateWaypoint 50 | { 51 | _active = NO; 52 | } 53 | 54 | @end 55 | -------------------------------------------------------------------------------- /Chapter08/Objective-C/SilverLine.h: -------------------------------------------------------------------------------- 1 | // 2 | // SilverLine.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/19/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | typedef enum NSUInteger 12 | { 13 | Wiehle_Reston_East = 1000, 14 | Spring_Hill = 1100, 15 | Greensboro = 1200, 16 | Tysons_Corner = 1300, 17 | McClean = 1400, 18 | East_Falls_Church = 2000, 19 | Ballston_MU = 2100, 20 | Virginia_Sq_GMU = 2200, 21 | Clarendon = 2300, 22 | Courthouse = 2400, 23 | Rosslyn = 3000, 24 | Foggy_Bottom_GWU = 3100, 25 | Farragut_West = 3200, 26 | McPherson_Sq = 3300, 27 | Metro_Center = 4000, 28 | Federal_Triangle = 4100, 29 | Smithsonian = 4200, 30 | LEnfant_Plaza = 5000, 31 | Federal_Center_SW = 5100, 32 | Capital_South = 5200, 33 | Eastern_Market = 5300, 34 | Potomac_Ave = 5400, 35 | Stadium_Armory = 6000, 36 | Benning_Road = 6100, 37 | Capital_Heights = 6200, 38 | Addison_Road = 6300, 39 | Morgan_Blvd = 6400, 40 | Largo_Town_Center = 6500 41 | } SilverLine; 42 | 43 | @interface SilverLineClass : NSObject 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /Chapter08/Objective-C/SilverLine.m: -------------------------------------------------------------------------------- 1 | // 2 | // SilverLine.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 9/19/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "SilverLine.h" 10 | 11 | @implementation SilverLineClass 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /Chapter08/Swift/SilverLine.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SilverLine.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 9/19/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public enum SilverLine : Int 12 | { 13 | case wiehle_Reston_East = 1000 14 | case spring_Hill = 1100 15 | case greensboro = 1200 16 | case tysons_Corner = 1300 17 | case mcClean = 1400 18 | case east_Falls_Church = 2000 19 | case ballston_MU = 2100 20 | case virginia_Sq_GMU = 2200 21 | case clarendon = 2300 22 | case courthouse = 2400 23 | case rosslyn = 3000 24 | case foggy_Bottom_GWU = 3100 25 | case farragut_West = 3200 26 | case mcPherson_Sq = 3300 27 | case metro_Center = 4000 28 | case federal_Triangle = 4100 29 | case smithsonian = 4200 30 | case lEnfant_Plaza = 5000 31 | case federal_Center_SW = 5100 32 | case capital_South = 5200 33 | case eastern_Market = 5300 34 | case potomac_Ave = 5400 35 | case stadium_Armory = 6000 36 | case benning_Road = 6100 37 | case capital_Heights = 6200 38 | case addison_Road = 6300 39 | case morgan_Blvd = 6400 40 | case largo_Town_Center = 6500 41 | } 42 | -------------------------------------------------------------------------------- /Chapter08/Swift/Waypoint.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Waypoint.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/24/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import CoreLocation 11 | 12 | public struct Waypoint : Equatable 13 | { 14 | var lat: Int 15 | var long: Int 16 | public fileprivate(set) var active: Bool 17 | 18 | public init(latitude: Int, longitude: Int) { 19 | lat = latitude 20 | long = longitude 21 | active = true 22 | } 23 | 24 | public mutating func DeactivateWaypoint() 25 | { 26 | active = false; 27 | } 28 | 29 | public mutating func ReactivateWaypoint() 30 | { 31 | active = true; 32 | } 33 | } 34 | 35 | public func == (lhs: Waypoint, rhs: Waypoint) -> Bool { 36 | return (lhs.lat == rhs.lat && lhs.long == rhs.long) 37 | } 38 | -------------------------------------------------------------------------------- /Chapter09/C#/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class Node 7 | { 8 | public Int16 Data; 9 | public Node Left; 10 | public Node Right; 11 | public List Children 12 | { 13 | get 14 | { 15 | List children = new List(); 16 | if (this.Left != null) 17 | { 18 | children.Add (this.Left); 19 | } 20 | if (this.Right != null) 21 | { 22 | children.Add (this.Right); 23 | } 24 | return children; 25 | } 26 | } 27 | 28 | public Node(Int16 data) 29 | { 30 | this.Data = data; 31 | } 32 | 33 | public bool InsertData(Int16 data) 34 | { 35 | Node node = new Node (data); 36 | return this.InsertNode(node); 37 | } 38 | 39 | public bool InsertNode(Node node) 40 | { 41 | if (node == null || node.Data == this.Data) 42 | { 43 | return false; 44 | } 45 | else if (node.Data < this.Data) 46 | { 47 | if (this.Left == null) 48 | { 49 | this.Left = node; 50 | return true; 51 | } 52 | else 53 | { 54 | return this.Left.InsertNode(node); 55 | } 56 | } 57 | else 58 | { 59 | if (this.Right == null) 60 | { 61 | this.Right = node; 62 | return true; 63 | } 64 | else 65 | { 66 | return this.Right.InsertNode(node); 67 | } 68 | } 69 | } 70 | 71 | public bool Graft(Node node) 72 | { 73 | if (node == null) 74 | { 75 | return false; 76 | } 77 | 78 | List nodes = node.ListTree(); 79 | foreach (Node n in nodes) 80 | { 81 | this.InsertNode(n); 82 | } 83 | 84 | return true; 85 | } 86 | 87 | public Node RemoveData(Int16 data) 88 | { 89 | Node node = new Node (data); 90 | return this.RemoveNode (node); 91 | } 92 | 93 | public Node RemoveNode(Node node) 94 | { 95 | if (node == null) 96 | { 97 | return null; 98 | } 99 | 100 | Node retNode; 101 | Node modNode; 102 | List treeList = new List(); 103 | 104 | if (this.Data == node.Data) 105 | { 106 | //Root match 107 | retNode = new Node(this.Data); 108 | modNode = this; 109 | if (this.Children.Count == 0) 110 | { 111 | return this; //Root has no childen 112 | } 113 | } 114 | else if (this.Left.Data == node.Data) 115 | { 116 | //Match found 117 | retNode = new Node(this.Left.Data); 118 | modNode = this.Left; 119 | } 120 | else if (this.Right.Data == node.Data) 121 | { 122 | //Match found 123 | retNode = new Node(this.Right.Data); 124 | modNode = this.Right; 125 | } 126 | else 127 | { 128 | foreach (Node child in this.Children) 129 | { 130 | if (child.RemoveNode(node) != null) 131 | { 132 | return child; 133 | } 134 | } 135 | 136 | //No match in tree 137 | return null; 138 | } 139 | 140 | //Reorder the tree 141 | if (modNode.Left != null) 142 | { 143 | modNode.Data = modNode.Left.Data; 144 | treeList.AddRange (modNode.Left.ListTree ()); 145 | modNode.Left = null; 146 | } 147 | else if (modNode.Right != null) 148 | { 149 | modNode.Data = modNode.Right.Data; 150 | treeList.AddRange (modNode.Right.ListTree ()); 151 | modNode.Right = null; 152 | } 153 | else 154 | { 155 | modNode = null; 156 | } 157 | 158 | foreach (Node n in treeList) 159 | { 160 | modNode.InsertNode(n); 161 | } 162 | 163 | //Finished 164 | return retNode; 165 | } 166 | 167 | public Node Prune(Node root) 168 | { 169 | if (root == null) 170 | { 171 | return null; 172 | } 173 | 174 | Node matchNode; 175 | if (this.Data == root.Data) 176 | { 177 | //Root match 178 | Node b = this.CopyTree(); 179 | this.Left = null; 180 | this.Right = null; 181 | return b; 182 | } 183 | else if (this.Left.Data == root.Data) 184 | { 185 | matchNode = this.Left; 186 | } 187 | else if (this.Right.Data == root.Data) 188 | { 189 | matchNode = this.Right; 190 | } 191 | else 192 | { 193 | foreach (Node child in this.Children) 194 | { 195 | if (child.Prune(root) != null) 196 | { 197 | return child; 198 | } 199 | } 200 | 201 | //No match in tree 202 | return null; 203 | } 204 | 205 | Node branch = matchNode.CopyTree(); 206 | matchNode = null; 207 | 208 | return branch; 209 | } 210 | 211 | public Node FindData(Int16 data) 212 | { 213 | Node node = new Node (data); 214 | return this.FindNode(node); 215 | } 216 | 217 | public Node FindNode(Node node) 218 | { 219 | if (node.Data == this.Data) 220 | { 221 | return this; 222 | } 223 | 224 | foreach (Node child in this.Children) 225 | { 226 | Node result = child.FindNode(node); 227 | if (result != null) 228 | { 229 | return result; 230 | } 231 | } 232 | 233 | return null; 234 | } 235 | 236 | public Node CopyTree() 237 | { 238 | Node n = new Node(this.Data); 239 | if (this.Left != null) 240 | { 241 | n.Left = this.Left.CopyTree(); 242 | } 243 | 244 | if(this.Right != null) 245 | { 246 | n.Right = this.Right.CopyTree(); 247 | } 248 | return n; 249 | } 250 | 251 | public List ListTree() 252 | { 253 | List result = new List(); 254 | result.Add(new Node(this.Data)); 255 | foreach (Node child in this.Children) 256 | { 257 | result.AddRange(child.ListTree()); 258 | } 259 | return result; 260 | } 261 | } 262 | } 263 | 264 | -------------------------------------------------------------------------------- /Chapter09/Java/Node.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.List; 4 | import java.util.LinkedList; 5 | 6 | /** 7 | * Created by William Smith on 9/24/16. 8 | */ 9 | public class Node { 10 | public int Data; 11 | public Node Left; 12 | public Node Right; 13 | 14 | public List getChildren() 15 | { 16 | List children = new LinkedList(); 17 | if (this.Left != null) 18 | { 19 | children.add(this.Left); 20 | } 21 | if (this.Right != null) 22 | { 23 | children.add(this.Right); 24 | } 25 | return children; 26 | } 27 | 28 | public Node(int data) 29 | { 30 | this.Data = data; 31 | } 32 | 33 | public boolean insertData(int data) 34 | { 35 | Node node = new Node (data); 36 | return this.insertNode(node); 37 | } 38 | 39 | public boolean insertNode(Node node) 40 | { 41 | if (node == null || node.Data == this.Data) 42 | { 43 | return false; 44 | } 45 | else if (node.Data < this.Data) 46 | { 47 | if (this.Left == null) 48 | { 49 | this.Left = node; 50 | return true; 51 | } 52 | else 53 | { 54 | return this.Left.insertNode(node); 55 | } 56 | } 57 | else 58 | { 59 | if (this.Right == null) 60 | { 61 | this.Right = node; 62 | return true; 63 | } 64 | else 65 | { 66 | return this.Right.insertNode(node); 67 | } 68 | } 69 | } 70 | 71 | public boolean graft(Node node) 72 | { 73 | if (node == null) 74 | { 75 | return false; 76 | } 77 | 78 | List nodes = node.listTree(); 79 | for (Node n : nodes) 80 | { 81 | this.insertNode(n); 82 | } 83 | 84 | return true; 85 | } 86 | 87 | public Node removeData(int data) 88 | { 89 | Node node = new Node(data); 90 | return this.removeNode(node); 91 | } 92 | 93 | public Node removeNode(Node node) 94 | { 95 | if (node == null) 96 | { 97 | return null; 98 | } 99 | 100 | Node retNode; 101 | Node modNode; 102 | List treeList = new LinkedList(); 103 | 104 | if (this.Data == node.Data) 105 | { 106 | //Root match 107 | retNode = new Node(this.Data); 108 | modNode = this; 109 | if (this.getChildren().size() == 0) 110 | { 111 | return this; //Root has no childen 112 | } 113 | } 114 | else if (this.Left.Data == node.Data) 115 | { 116 | //Match found 117 | retNode = new Node(this.Left.Data); 118 | modNode = this.Left; 119 | } 120 | else if (this.Right.Data == node.Data) 121 | { 122 | //Match found 123 | retNode = new Node(this.Right.Data); 124 | modNode = this.Right; 125 | } 126 | else 127 | { 128 | for (Node child : this.getChildren()) 129 | { 130 | if (child.removeNode(node) != null) 131 | { 132 | return child; 133 | } 134 | } 135 | 136 | //No match in tree 137 | return null; 138 | } 139 | 140 | //Reorder the tree 141 | if (modNode.Left != null) 142 | { 143 | modNode.Data = modNode.Left.Data; 144 | treeList.addAll(modNode.Left.listTree()); 145 | modNode.Left = null; 146 | } 147 | else if (modNode.Right != null) 148 | { 149 | modNode.Data = modNode.Right.Data; 150 | treeList.addAll(modNode.Right.listTree()); 151 | modNode.Right = null; 152 | } 153 | else 154 | { 155 | modNode = null; 156 | } 157 | 158 | for (Node n : treeList) 159 | { 160 | modNode.insertNode(n); 161 | } 162 | 163 | //Finished 164 | return retNode; 165 | } 166 | 167 | public Node prune(Node root) 168 | { 169 | if (root == null) 170 | { 171 | return null; 172 | } 173 | 174 | Node matchNode; 175 | if (this.Data == root.Data) 176 | { 177 | //Root match 178 | Node b = this.copyTree(); 179 | this.Left = null; 180 | this.Right = null; 181 | return b; 182 | } 183 | else if (this.Left.Data == root.Data) 184 | { 185 | matchNode = this.Left; 186 | } 187 | else if (this.Right.Data == root.Data) 188 | { 189 | matchNode = this.Right; 190 | } 191 | else 192 | { 193 | for (Node child : this.getChildren()) 194 | { 195 | if (child.prune(root) != null) 196 | { 197 | return child; 198 | } 199 | } 200 | 201 | //No match in tree 202 | return null; 203 | } 204 | 205 | Node branch = matchNode.copyTree(); 206 | matchNode = null; 207 | 208 | return branch; 209 | } 210 | 211 | public Node findData(int data) 212 | { 213 | Node node = new Node (data); 214 | return this.findNode(node); 215 | } 216 | 217 | public Node findNode(Node node) 218 | { 219 | if (node.Data == this.Data) 220 | { 221 | return this; 222 | } 223 | 224 | for (Node child : this.getChildren()) 225 | { 226 | Node result = child.findNode(node); 227 | if (result != null) 228 | { 229 | return result; 230 | } 231 | } 232 | 233 | return null; 234 | } 235 | 236 | public Node copyTree() 237 | { 238 | Node n = new Node(this.Data); 239 | if (this.Left != null) 240 | { 241 | n.Left = this.Left.copyTree(); 242 | } 243 | 244 | if(this.Right != null) 245 | { 246 | n.Right = this.Right.copyTree(); 247 | } 248 | return n; 249 | } 250 | 251 | public List listTree() { 252 | List result = new LinkedList(); 253 | result.add(new Node(this.Data)); 254 | for (Node child : this.getChildren()) 255 | { 256 | result.addAll(child.listTree()); 257 | } 258 | return result; 259 | } 260 | } 261 | -------------------------------------------------------------------------------- /Chapter09/Objective-C/EDSNode.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSNode.h 3 | // EverydayDataStructures 4 | // 5 | // Created by Will Smith on 9/24/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSNode : NSObject 12 | 13 | @property (nonatomic) NSInteger data; 14 | @property (nonatomic) EDSNode *left; 15 | @property (nonatomic) EDSNode *right; 16 | @property (nonatomic, readonly) NSArray *children; 17 | 18 | -(instancetype)initNodeWithData:(NSInteger)data; 19 | 20 | -(BOOL)insertData:(NSInteger)data; 21 | -(BOOL)insertNode:(EDSNode*)node; 22 | -(BOOL)graft:(EDSNode*)node; 23 | -(EDSNode*)removeData:(NSInteger)data; 24 | -(EDSNode*)removeNode:(EDSNode*)node; 25 | -(EDSNode*)prune:(EDSNode*)root; 26 | -(EDSNode*)findData:(NSInteger)data; 27 | -(EDSNode*)findNode:(EDSNode*)node; 28 | -(EDSNode*)copyTree; 29 | -(NSArray*)listTree; 30 | 31 | @end 32 | -------------------------------------------------------------------------------- /Chapter09/Objective-C/EDSNode.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSNode.m 3 | // EverydayDataStructures 4 | // 5 | // Created by Will Smith on 9/24/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSNode.h" 10 | 11 | @implementation EDSNode 12 | 13 | -(instancetype)initNodeWithData:(NSInteger)data 14 | { 15 | if (self = [super init]) 16 | { 17 | _data = data; 18 | } 19 | return self; 20 | } 21 | 22 | -(NSInteger)data 23 | { 24 | return _data; 25 | } 26 | 27 | -(EDSNode*)left 28 | { 29 | return _left; 30 | } 31 | 32 | -(EDSNode*)right 33 | { 34 | return _right; 35 | } 36 | 37 | -(NSArray*)children 38 | { 39 | return [NSArray arrayWithObjects:_left, _right, nil]; 40 | } 41 | 42 | -(BOOL)insertData:(NSInteger)data 43 | { 44 | EDSNode *node = [[EDSNode alloc] initNodeWithData:data]; 45 | return [self insertNode:node]; 46 | } 47 | 48 | -(BOOL)insertNode:(EDSNode*)node 49 | { 50 | if (!node || [self findNode:node]) 51 | { 52 | return NO; 53 | } 54 | else if (node.data < _data) 55 | { 56 | if (!_left) 57 | { 58 | _left = node; 59 | return YES; 60 | } 61 | else 62 | { 63 | return [_left insertNode:node]; 64 | } 65 | } 66 | else 67 | { 68 | if (!_right) 69 | { 70 | _right = node; 71 | return YES; 72 | } 73 | else 74 | { 75 | return [_right insertNode:node]; 76 | } 77 | } 78 | } 79 | 80 | -(BOOL)graft:(EDSNode*)node 81 | { 82 | if (!node) 83 | { 84 | return NO; 85 | } 86 | 87 | NSArray *nodes = [node listTree]; 88 | for (EDSNode *n in nodes) 89 | { 90 | [self insertNode:n]; 91 | } 92 | 93 | return true; 94 | } 95 | 96 | -(EDSNode*)removeData:(NSInteger)data 97 | { 98 | EDSNode *node = [[EDSNode alloc] initNodeWithData:data]; 99 | return [self removeNode:node]; 100 | } 101 | 102 | -(EDSNode*)removeNode:(EDSNode*)node 103 | { 104 | if (!node) 105 | { 106 | return NO; 107 | } 108 | 109 | EDSNode *retNode; 110 | EDSNode *modNode; 111 | NSMutableArray *treeList = [NSMutableArray array]; 112 | 113 | if (self.data == node.data) 114 | { 115 | //Root match 116 | retNode = [[EDSNode alloc] initNodeWithData:self.data]; 117 | modNode = self; 118 | if ([self.children count] == 0) 119 | { 120 | return self; //Root has no childen 121 | } 122 | } 123 | else if (_left.data == node.data) 124 | { 125 | //Match found 126 | retNode = [[EDSNode alloc] initNodeWithData:_left.data]; 127 | modNode = _left; 128 | } 129 | else if (_right.data == node.data) 130 | { 131 | //Match found 132 | retNode = [[EDSNode alloc] initNodeWithData:_right.data]; 133 | modNode = _right; 134 | } 135 | else 136 | { 137 | for (EDSNode *child in self.children) 138 | { 139 | if ([child removeNode:node]) 140 | { 141 | return child; 142 | } 143 | } 144 | 145 | //No match in tree 146 | return nil; 147 | } 148 | 149 | //Reorder the tree 150 | if (modNode.left) 151 | { 152 | modNode.data = modNode.left.data; 153 | [treeList addObjectsFromArray:[modNode.left listTree]]; 154 | modNode.left = nil; 155 | } 156 | else if (modNode.right) 157 | { 158 | modNode.data = modNode.right.data; 159 | [treeList addObjectsFromArray:[modNode.right listTree]]; 160 | modNode.right = nil; 161 | } 162 | else 163 | { 164 | modNode = nil; 165 | } 166 | 167 | for (EDSNode *n in treeList) 168 | { 169 | [modNode insertNode:n]; 170 | } 171 | 172 | //Finished 173 | return retNode; 174 | } 175 | 176 | -(EDSNode*)prune:(EDSNode*)root 177 | { 178 | if (!root) 179 | { 180 | return nil; 181 | } 182 | 183 | EDSNode *matchNode; 184 | if (self.data == root.data) 185 | { 186 | //Root match 187 | EDSNode *b = [self copyTree]; 188 | self.left = nil; 189 | self.right = nil; 190 | return b; 191 | } 192 | else if (self.left.data == root.data) 193 | { 194 | matchNode = self.left; 195 | } 196 | else if (self.right.data == root.data) 197 | { 198 | matchNode = self.right; 199 | } 200 | else 201 | { 202 | for (EDSNode *child in self.children) 203 | { 204 | if ([child prune:root]) 205 | { 206 | return child; 207 | } 208 | } 209 | 210 | //No match in tree 211 | return nil; 212 | } 213 | 214 | EDSNode *branch = [matchNode copyTree]; 215 | matchNode = nil; 216 | 217 | return branch; 218 | } 219 | 220 | -(EDSNode*)findData:(NSInteger)data 221 | { 222 | EDSNode *node = [[EDSNode alloc] initNodeWithData:data]; 223 | return [self findNode:node]; 224 | } 225 | 226 | -(EDSNode*)findNode:(EDSNode*)node 227 | { 228 | if (node.data == self.data) 229 | { 230 | return self; 231 | } 232 | 233 | for (EDSNode *child in self.children) 234 | { 235 | EDSNode *result = [child findNode:node]; 236 | if (result) 237 | { 238 | return result; 239 | } 240 | } 241 | 242 | return nil; 243 | } 244 | 245 | -(EDSNode*)copyTree 246 | { 247 | EDSNode *n = [[EDSNode alloc] initNodeWithData:self.data]; 248 | if (self.left) 249 | { 250 | n.left = [self.left copyTree]; 251 | } 252 | 253 | if(self.right) 254 | { 255 | n.right = [self.right copyTree]; 256 | } 257 | return n; 258 | } 259 | 260 | -(NSArray*)listTree 261 | { 262 | NSMutableArray *result = [NSMutableArray array]; 263 | [result addObject:[[EDSNode alloc] initNodeWithData:self.data]]; 264 | for (EDSNode *child in self.children) { 265 | [result addObjectsFromArray:[child listTree]]; 266 | } 267 | return [result copy]; 268 | } 269 | 270 | @end 271 | -------------------------------------------------------------------------------- /Chapter09/Swift/Node.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Node.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by Will Smith on 9/24/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public class Node : Equatable 12 | { 13 | public var data: Int 14 | public var left: Node? 15 | public var right: Node? 16 | 17 | public var children: Array { 18 | return [left!, right!] 19 | } 20 | 21 | public init (nodeData: Int) 22 | { 23 | data = nodeData 24 | } 25 | 26 | 27 | public func insertData(data: Int) -> Bool 28 | { 29 | return insertNode(node: Node(nodeData:data)) 30 | } 31 | 32 | public func insertNode(node: Node?) -> Bool 33 | { 34 | if (node == nil) 35 | { 36 | return false 37 | } 38 | 39 | if ((findNode(node: node!)) != nil) 40 | { 41 | return false 42 | } 43 | else if (node!.data < data) 44 | { 45 | if (left == nil) 46 | { 47 | left = node 48 | return true 49 | } 50 | else 51 | { 52 | return left!.insertNode(node: node) 53 | } 54 | } 55 | else 56 | { 57 | if (right == node) 58 | { 59 | right = node 60 | return true 61 | } 62 | else 63 | { 64 | return right!.insertNode(node: node) 65 | } 66 | } 67 | } 68 | 69 | 70 | public func graft(node: Node?) -> Bool 71 | { 72 | if (node == nil) 73 | { 74 | return false 75 | } 76 | 77 | let nodes: Array = node!.listTree() 78 | for n in nodes 79 | { 80 | self.insertNode(node: n) 81 | } 82 | 83 | return true 84 | } 85 | 86 | public func removeData(data: Int) -> Node? 87 | { 88 | return removeNode(node: Node(nodeData:data)) 89 | } 90 | 91 | public func removeNode(node: Node?) -> Node? 92 | { 93 | if (node == nil) 94 | { 95 | return nil 96 | } 97 | 98 | var retNode: Node 99 | var modNode: Node? 100 | var treeList = Array() 101 | 102 | if (self.data == node!.data) 103 | { 104 | //Root match 105 | retNode = Node(nodeData: self.data) 106 | modNode = self 107 | if (children.count == 0) 108 | { 109 | return self //Root has no childen 110 | } 111 | } 112 | else if (left!.data == node!.data) 113 | { 114 | //Match found 115 | retNode = Node(nodeData: left!.data) 116 | modNode = left! 117 | } 118 | else if (right!.data == node!.data) 119 | { 120 | //Match found 121 | retNode = Node(nodeData: right!.data) 122 | modNode = right! 123 | } 124 | else 125 | { 126 | for child in self.children 127 | { 128 | if (child.removeNode(node: node) != nil) 129 | { 130 | return child 131 | } 132 | } 133 | 134 | //No match in tree 135 | return nil 136 | } 137 | 138 | //Reorder the tree 139 | if ((modNode!.left) != nil) 140 | { 141 | modNode!.data = modNode!.left!.data 142 | treeList = modNode!.left!.listTree() 143 | modNode!.left = nil 144 | } 145 | else if ((modNode!.right) != nil) 146 | { 147 | modNode!.data = modNode!.right!.data 148 | treeList = modNode!.right!.listTree() 149 | modNode!.right = nil 150 | } 151 | else 152 | { 153 | modNode = nil 154 | } 155 | 156 | for n in treeList 157 | { 158 | modNode!.insertNode(node: n) 159 | } 160 | 161 | //Finished 162 | return retNode 163 | } 164 | 165 | public func prune(root: Node?) -> Node? 166 | { 167 | if (root == nil) 168 | { 169 | return nil 170 | } 171 | 172 | var matchNode: Node? 173 | if (self.data == root!.data) 174 | { 175 | //Root match 176 | let b = self.copyTree() 177 | self.left = nil 178 | self.right = nil 179 | return b 180 | } 181 | else if (self.left!.data == root!.data) 182 | { 183 | matchNode = self.left! 184 | } 185 | else if (self.right!.data == root!.data) 186 | { 187 | matchNode = self.right! 188 | } 189 | else 190 | { 191 | for child in self.children 192 | { 193 | if (child.prune(root: root!) != nil) 194 | { 195 | return child 196 | } 197 | } 198 | 199 | //No match in tree 200 | return nil; 201 | } 202 | 203 | let branch = matchNode!.copyTree() 204 | matchNode = nil 205 | 206 | return branch 207 | } 208 | 209 | public func findData(data: Int) -> Node? 210 | { 211 | return findNode(node: Node(nodeData:data)) 212 | } 213 | 214 | public func findNode(node: Node) -> Node? 215 | { 216 | if (node == self) 217 | { 218 | return self 219 | } 220 | 221 | for child in children 222 | { 223 | let result = child.findNode(node: node) 224 | if (result != nil) 225 | { 226 | return result 227 | } 228 | } 229 | 230 | return nil 231 | } 232 | 233 | public func copyTree() -> Node 234 | { 235 | let n = Node(nodeData: self.data) 236 | 237 | if (self.left != nil) 238 | { 239 | n.left = self.left!.copyTree() 240 | } 241 | 242 | if(self.right != nil) 243 | { 244 | n.right = self.right!.copyTree() 245 | } 246 | 247 | return n 248 | } 249 | 250 | public func listTree() -> Array 251 | { 252 | var result = Array() 253 | result.append(self) 254 | for child in children 255 | { 256 | result.append(contentsOf: child.listTree()) 257 | } 258 | return result 259 | } 260 | } 261 | 262 | public func == (lhs: Node, rhs: Node) -> Bool { 263 | return (lhs.data == rhs.data) 264 | } 265 | -------------------------------------------------------------------------------- /Chapter10/C#/Heap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class HeapNode 7 | { 8 | public int Data; 9 | } 10 | 11 | public class MinHeap 12 | { 13 | List elements; 14 | 15 | public int Count 16 | { 17 | get 18 | { 19 | return elements.Count; 20 | } 21 | } 22 | 23 | public MinHeap() 24 | { 25 | elements = new List(); 26 | } 27 | 28 | public void Insert(HeapNode item) 29 | { 30 | elements.Add(item); 31 | OrderHeap(); 32 | } 33 | 34 | public void Delete(HeapNode item) 35 | { 36 | int i = elements.IndexOf(item); 37 | int last = elements.Count - 1; 38 | 39 | elements[i] = elements[last]; 40 | elements.RemoveAt(last); 41 | OrderHeap(); 42 | } 43 | 44 | public HeapNode ExtractMin() //Pop 45 | { 46 | if (elements.Count > 0) 47 | { 48 | HeapNode item = elements[0]; 49 | Delete(item); 50 | return item; 51 | } 52 | 53 | return null; 54 | } 55 | 56 | public HeapNode FindMin() //Peek 57 | { 58 | if (elements.Count > 0) 59 | { 60 | return elements[0]; 61 | } 62 | 63 | return null; 64 | } 65 | 66 | private void OrderHeap() 67 | { 68 | for (int i = elements.Count - 1; i > 0; i--) 69 | { 70 | int parentPosition = (i - 1) / 2; 71 | 72 | if (elements[parentPosition].Data > elements[i].Data) 73 | { 74 | SwapElements(parentPosition, i); 75 | } 76 | } 77 | } 78 | 79 | private void SwapElements(int firstIndex, int secondIndex) 80 | { 81 | HeapNode tmp = elements[firstIndex]; 82 | elements[firstIndex] = elements[secondIndex]; 83 | elements[secondIndex] = tmp; 84 | } 85 | 86 | public List GetChildren(int parentIndex) 87 | { 88 | if (parentIndex >= 0) 89 | { 90 | List children = new List(); 91 | int childIndexOne = (2 * parentIndex) + 1; 92 | int childIndexTwo = (2 * parentIndex) + 2; 93 | children.Add(elements[childIndexOne]); 94 | children.Add(elements[childIndexTwo]); 95 | 96 | return children; 97 | } 98 | 99 | return null; 100 | } 101 | 102 | public HeapNode GetParent(int childIndex) 103 | { 104 | if (childIndex > 0 && elements.Count > childIndex) 105 | { 106 | int parentIndex = (childIndex - 1) / 2; 107 | return elements[parentIndex]; 108 | } 109 | 110 | return null; 111 | } 112 | 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Chapter10/Java/HeapNode.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /** 4 | * Created by William Smith on 10/4/16. 5 | */ 6 | public class HeapNode { 7 | public int Data; 8 | } 9 | -------------------------------------------------------------------------------- /Chapter10/Java/MinHeap.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * Created by William Smith on 10/2/16. 7 | */ 8 | public class MinHeap 9 | { 10 | List elements; 11 | 12 | public int size() 13 | { 14 | return elements.size(); 15 | } 16 | 17 | public MinHeap() 18 | { 19 | elements = new ArrayList(); 20 | } 21 | 22 | public void insert(HeapNode item) 23 | { 24 | elements.add(item); 25 | orderHeap(); 26 | } 27 | 28 | public void delete(HeapNode item) 29 | { 30 | int i = elements.indexOf(item); 31 | int last = elements.size() - 1; 32 | 33 | elements.set(i, elements.get(last)); 34 | elements.remove(last); 35 | orderHeap(); 36 | } 37 | 38 | public HeapNode extractMin() //Pop 39 | { 40 | if (elements.size() > 0) 41 | { 42 | HeapNode item = elements.get(0); 43 | delete(item); 44 | return item; 45 | } 46 | 47 | return null; 48 | } 49 | 50 | public HeapNode findMin() //Peek 51 | { 52 | if (elements.size() > 0) 53 | { 54 | return elements.get(0); 55 | } 56 | 57 | return null; 58 | } 59 | 60 | private void orderHeap() 61 | { 62 | for (int i = elements.size() - 1; i > 0; i--) 63 | { 64 | int parentPosition = (i - 1) / 2; 65 | 66 | if (elements.get(parentPosition).Data > elements.get(i).Data) 67 | { 68 | swapElements(parentPosition, i); 69 | } 70 | } 71 | } 72 | 73 | private void swapElements(int firstIndex, int secondIndex) 74 | { 75 | HeapNode tmp = elements.get(firstIndex); 76 | elements.set(firstIndex, elements.get(secondIndex)); 77 | elements.set(secondIndex, tmp); 78 | } 79 | 80 | public List getChildren(int parentIndex) 81 | { 82 | if (parentIndex >= 0) 83 | { 84 | ArrayList children = new ArrayList(); 85 | int childIndexOne = (2 * parentIndex) + 1; 86 | int childIndexTwo = (2 * parentIndex) + 2; 87 | children.add(elements.get(childIndexOne)); 88 | children.add(elements.get(childIndexTwo)); 89 | 90 | return children; 91 | } 92 | 93 | return null; 94 | } 95 | 96 | public HeapNode getParent(int childIndex) 97 | { 98 | if (childIndex > 0 && elements.size() > childIndex) 99 | { 100 | int parentIndex = (childIndex - 1) / 2; 101 | return elements.get(parentIndex); 102 | } 103 | 104 | return null; 105 | } 106 | 107 | } -------------------------------------------------------------------------------- /Chapter10/Objective-C/EDSMinHeap.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSMinHeap.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/6/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSHeapNode; 12 | 13 | @interface EDSMinHeap : NSObject 14 | 15 | @property NSInteger Count; 16 | 17 | -(instancetype)initMinHeap; 18 | -(void)insert:(EDSHeapNode*)item; 19 | -(void)delete:(EDSHeapNode*)item; 20 | -(EDSHeapNode*)extractMin; //Pop 21 | -(EDSHeapNode*)findMin; //Peek 22 | -(NSArray*)childrenOfParentIndex:(NSInteger)parentIndex; 23 | -(EDSHeapNode*)parentOfChildIndex:(NSInteger)childIndex; 24 | 25 | @end 26 | 27 | 28 | @interface EDSHeapNode : NSObject 29 | 30 | @property NSInteger data; 31 | 32 | @end 33 | -------------------------------------------------------------------------------- /Chapter10/Objective-C/EDSMinHeap.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSMinHeap.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/6/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSMinHeap.h" 10 | @interface EDSMinHeap() 11 | { 12 | NSMutableArray *_elements; 13 | } 14 | 15 | @end 16 | 17 | @implementation EDSMinHeap 18 | 19 | -(instancetype)initMinHeap{ 20 | 21 | if (self = [super init]) 22 | { 23 | _elements = [NSMutableArray array]; 24 | } 25 | 26 | return self; 27 | } 28 | 29 | -(NSInteger)getCount 30 | { 31 | return [_elements count]; 32 | } 33 | 34 | -(void)insert:(EDSHeapNode*)item 35 | { 36 | [_elements addObject:item]; 37 | [self orderHeap]; 38 | } 39 | 40 | -(void)delete:(EDSHeapNode*)item 41 | { 42 | long i = [_elements indexOfObject:item]; 43 | 44 | _elements[i] = [_elements lastObject]; 45 | [_elements removeLastObject]; 46 | [self orderHeap]; 47 | } 48 | 49 | -(EDSHeapNode*)extractMin 50 | { 51 | if ([_elements count] > 0) 52 | { 53 | EDSHeapNode *item = _elements[0]; 54 | [self delete:item]; 55 | return item; 56 | } 57 | 58 | return nil; 59 | } 60 | 61 | -(EDSHeapNode*)findMin 62 | { 63 | if ([_elements count] > 0) 64 | { 65 | return _elements[0]; 66 | } 67 | 68 | return nil; 69 | } 70 | 71 | -(void)orderHeap 72 | { 73 | for (long i = [_elements count] - 1; i > 0; i--) 74 | { 75 | long parentPosition = (i - 1) / 2; 76 | 77 | if (_elements[parentPosition].data > _elements[i].data) 78 | { 79 | [self swapElement:parentPosition withElement:i]; 80 | } 81 | } 82 | } 83 | 84 | -(void)swapElement:(long)firstIndex withElement:(long)secondIndex 85 | { 86 | EDSHeapNode *tmp = _elements[firstIndex]; 87 | _elements[firstIndex] = _elements[secondIndex]; 88 | _elements[secondIndex] = tmp; 89 | } 90 | 91 | -(NSArray*)childrenOfParentIndex:(NSInteger)parentIndex 92 | { 93 | if (parentIndex >= 0) 94 | { 95 | NSMutableArray *children = [NSMutableArray array]; 96 | long childIndexOne = (2 * parentIndex) + 1; 97 | long childIndexTwo = (2 * parentIndex) + 2; 98 | [children addObject:_elements[childIndexOne]]; 99 | [children addObject:_elements[childIndexTwo]]; 100 | 101 | return children; 102 | } 103 | 104 | return nil; 105 | } 106 | 107 | -(EDSHeapNode*)parentOfChildIndex:(NSInteger)childIndex 108 | { 109 | if (childIndex > 0 && [_elements count] > childIndex) 110 | { 111 | long parentIndex = (childIndex - 1) / 2; 112 | return _elements[parentIndex]; 113 | } 114 | 115 | return nil; 116 | } 117 | @end 118 | -------------------------------------------------------------------------------- /Chapter10/Swift/MinHeap.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MinHeap.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 10/6/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public class MinHeap 12 | { 13 | public var _elements: Array = [HeapNode]() 14 | 15 | 16 | public init () {} 17 | 18 | public func getCount() -> Int 19 | { 20 | return _elements.count 21 | } 22 | 23 | public func insert(item: HeapNode) 24 | { 25 | _elements.append(item) 26 | orderHeap() 27 | } 28 | 29 | public func delete(item: HeapNode) 30 | { 31 | if let index = _elements.index(of: item) 32 | { 33 | _elements[index] = _elements.last! 34 | _elements.removeLast() 35 | orderHeap() 36 | } 37 | } 38 | 39 | public func extractMin() -> HeapNode? 40 | { 41 | if (_elements.count > 0) 42 | { 43 | let item = _elements[0] 44 | delete(item: item) 45 | return item 46 | } 47 | 48 | return nil 49 | } 50 | 51 | public func findMin() -> HeapNode? 52 | { 53 | if (_elements.count > 0) 54 | { 55 | return _elements[0] 56 | } 57 | 58 | return nil 59 | } 60 | 61 | public func orderHeap() 62 | { 63 | for i in (0..<(_elements.count) - 1).reversed() 64 | { 65 | let parentPosition = (i - 1) / 2 66 | 67 | if (_elements[parentPosition].data! > _elements[i].data!) 68 | { 69 | swapElements(first: parentPosition, second: i) 70 | } 71 | } 72 | } 73 | 74 | public func swapElements(first: Int, second: Int) 75 | { 76 | let tmp = _elements[first] 77 | _elements[first] = _elements[second] 78 | _elements[second] = tmp 79 | } 80 | 81 | public func getChildren(parentIndex: Int) -> [HeapNode]? 82 | { 83 | if (parentIndex >= 0) 84 | { 85 | var children: Array = [HeapNode]() 86 | 87 | let childIndexOne = (2 * parentIndex) + 1; 88 | let childIndexTwo = (2 * parentIndex) + 2; 89 | children.append(_elements[childIndexOne]) 90 | children.append(_elements[childIndexTwo]) 91 | 92 | return children; 93 | } 94 | 95 | return nil; 96 | } 97 | 98 | public func getParent(childIndex: Int) -> HeapNode? 99 | { 100 | if (childIndex > 0 && _elements.count > childIndex) 101 | { 102 | let parentIndex = (childIndex - 1) / 2; 103 | return _elements[parentIndex]; 104 | } 105 | 106 | return nil; 107 | } 108 | } 109 | 110 | public class HeapNode : Equatable 111 | { 112 | public var data: Int? 113 | 114 | public init() {} 115 | } 116 | 117 | public func == (lhs: HeapNode, rhs: HeapNode) -> Bool { 118 | return (lhs.data == rhs.data) 119 | } 120 | -------------------------------------------------------------------------------- /Chapter11/C#/Graph.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class Graph 7 | { 8 | private List _nodes; 9 | public List Nodes 10 | { 11 | get 12 | { 13 | return _nodes; 14 | } 15 | } 16 | 17 | public Graph(List nodes) 18 | { 19 | if (nodes == null) 20 | { 21 | _nodes = new List(); 22 | } 23 | else 24 | { 25 | _nodes = nodes; 26 | } 27 | } 28 | 29 | public void AddNode(GraphNode node) 30 | { 31 | _nodes.Add(node); 32 | } 33 | 34 | public void AddNodeForValue(Int16 value) 35 | { 36 | // adds a node to the graph 37 | _nodes.Add(new GraphNode(value)); 38 | } 39 | 40 | public bool RemoveNode(Int16 value) 41 | { 42 | // first remove the node from the nodeset 43 | GraphNode nodeToRemove = _nodes.Find(n => n.Value == value); 44 | if (nodeToRemove == null) 45 | { 46 | return false; 47 | } 48 | 49 | // otherwise, the node was found 50 | _nodes.Remove(nodeToRemove); 51 | 52 | // enumerate through each node in the nodeSet, removing edges to this node 53 | foreach (GraphNode node in _nodes) 54 | { 55 | int index = node.Neighbors.IndexOf(nodeToRemove); 56 | if (index != -1) 57 | { 58 | // remove the reference to the node and associated cost 59 | node.Neighbors.RemoveAt(index); 60 | } 61 | } 62 | 63 | return true; 64 | } 65 | 66 | 67 | public void AddEdge(GraphNode from, GraphNode to) 68 | { 69 | from.Neighbors.Add(to); 70 | } 71 | 72 | public void AddBidirectedEdge(GraphNode from, GraphNode to) 73 | { 74 | from.Neighbors.Add(to); 75 | to.Neighbors.Add(from); 76 | } 77 | 78 | public bool Adjacent(GraphNode from, GraphNode to) 79 | { 80 | return from.Neighbors.Contains(to); 81 | } 82 | 83 | public List Neighbors(Int16 value) 84 | { 85 | 86 | GraphNode node = _nodes.Find(n => n.Value == value); 87 | if (node == null) 88 | { 89 | return null; 90 | } 91 | else 92 | { 93 | return node.Neighbors; 94 | } 95 | } 96 | 97 | public int Count 98 | { 99 | get 100 | { 101 | return _nodes.Count; 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Chapter11/C#/GraphNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class GraphNode 7 | { 8 | public Int16 Value; 9 | 10 | //private List _neighbors; 11 | public List Neighbors; 12 | 13 | public GraphNode() 14 | { 15 | // _neighbors = new List(); 16 | } 17 | 18 | public GraphNode(Int16 value) 19 | { 20 | // _neighbors = new List(); 21 | Value = value; 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter11/Java/Graph.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.LinkedList; 4 | 5 | /** 6 | * Created by William Smith on 10/14/16. 7 | */ 8 | public class Graph 9 | { 10 | private LinkedList _nodes; 11 | public LinkedList GetNodes() 12 | { 13 | return _nodes; 14 | } 15 | 16 | public Graph(LinkedList nodes) 17 | { 18 | if (nodes == null) 19 | { 20 | _nodes = new LinkedList(); 21 | } 22 | else 23 | { 24 | _nodes = nodes; 25 | } 26 | } 27 | 28 | public void AddNode(GraphNode node) 29 | { 30 | _nodes.add(node); 31 | } 32 | 33 | public void AddNodeForValue(int value) 34 | { 35 | _nodes.add(new GraphNode(value)); 36 | } 37 | 38 | public boolean RemoveNode(int value) 39 | { 40 | GraphNode nodeToRemove = null; 41 | for (GraphNode node : _nodes) 42 | { 43 | if (node.Value == value) 44 | { 45 | nodeToRemove = node; 46 | break; 47 | } 48 | } 49 | 50 | if (nodeToRemove == null) 51 | { 52 | return false; 53 | } 54 | 55 | _nodes.remove(nodeToRemove); 56 | 57 | for (GraphNode node : _nodes) 58 | { 59 | int index = node.GetNeighbors().indexOf(nodeToRemove); 60 | if (index != -1) 61 | { 62 | node.GetNeighbors().remove(index); 63 | } 64 | } 65 | 66 | return true; 67 | } 68 | 69 | 70 | public void AddEdge(GraphNode from, GraphNode to) 71 | { 72 | from.GetNeighbors().add(to); 73 | } 74 | 75 | public void AddBidirectedEdge(GraphNode from, GraphNode to) 76 | { 77 | from.GetNeighbors().add(to); 78 | to.GetNeighbors().add(from); 79 | } 80 | 81 | public boolean Adjacent(GraphNode from, GraphNode to) 82 | { 83 | return from.GetNeighbors().contains(to); 84 | } 85 | 86 | public LinkedList Neighbors(int value) 87 | { 88 | GraphNode node = null; 89 | for (GraphNode n : _nodes) 90 | { 91 | if (n.Value == value) 92 | { 93 | node = n; 94 | break; 95 | } 96 | } 97 | 98 | if (node == null) 99 | { 100 | return null; 101 | } 102 | else 103 | { 104 | return node.GetNeighbors(); 105 | } 106 | } 107 | 108 | public int GetCount() 109 | { 110 | return _nodes.size(); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Chapter11/Java/GraphNode.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.LinkedList; 4 | 5 | /** 6 | * Created by William Smith on 10/14/16. 7 | */ 8 | public class GraphNode 9 | { 10 | public int Value; 11 | 12 | private LinkedList _neighbors; 13 | public LinkedList GetNeighbors() 14 | { 15 | return _neighbors; 16 | } 17 | 18 | public GraphNode() 19 | { 20 | _neighbors = new LinkedList(); 21 | } 22 | 23 | public GraphNode(int value) 24 | { 25 | _neighbors = new LinkedList(); 26 | Value = value; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter11/Objective-C/EDSGraph.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSGraph.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/14/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSGraphNode; 12 | 13 | @interface EDSGraph : NSObject 14 | 15 | @property (nonatomic) NSMutableArray *nodes; 16 | @property (nonatomic, readonly) NSInteger *count; 17 | 18 | -(instancetype)initGraphWithNodes:(NSMutableArray*)nodes; 19 | 20 | -(void)addNode:(EDSGraphNode*)node; 21 | -(void)addNodeForValue:(NSInteger)value; 22 | -(BOOL)removeNodeForValue:(NSInteger)value; 23 | -(void)addEdgeFromNode:(EDSGraphNode*)from toNode:(EDSGraphNode*)to; 24 | -(void)addBidirectionalEdgeFromNode:(EDSGraphNode*)from toNode:(EDSGraphNode*)to; 25 | -(BOOL)adjacent:(EDSGraphNode*)from toNode:(EDSGraphNode*)to; 26 | -(NSMutableArray*)neighborsOfValue:(NSInteger)value; 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /Chapter11/Objective-C/EDSGraph.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSGraph.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/14/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSGraph.h" 10 | #import "EDSGraphNode.h" 11 | 12 | @interface EDSGraph() 13 | { 14 | NSMutableArray* _nodes; 15 | } 16 | 17 | @end 18 | 19 | @implementation EDSGraph 20 | 21 | -(instancetype)initGraphWithNodes:(NSMutableArray *)nodes 22 | { 23 | if (self = [super init]) 24 | { 25 | if (nodes) 26 | { 27 | _nodes = nodes; 28 | } 29 | else 30 | { 31 | _nodes = [NSMutableArray array]; 32 | } 33 | } 34 | return self; 35 | } 36 | 37 | -(NSMutableArray*)nodes 38 | { 39 | return _nodes; 40 | } 41 | 42 | -(NSInteger)countOfNodes 43 | { 44 | return [_nodes count]; 45 | } 46 | 47 | -(void)addNode:(EDSGraphNode*)node 48 | { 49 | [_nodes addObject:node]; 50 | } 51 | 52 | -(void)addNodeForValue:(NSInteger)value 53 | { 54 | EDSGraphNode *node = [[EDSGraphNode alloc] initGraphNodeWithValue:value]; 55 | [_nodes addObject:node]; 56 | } 57 | 58 | -(BOOL)removeNodeForValue:(NSInteger)value 59 | { 60 | EDSGraphNode *nodeToRemove; 61 | for (EDSGraphNode *n in _nodes) 62 | { 63 | if (n.value == value) 64 | { 65 | nodeToRemove = n; 66 | break; 67 | } 68 | } 69 | 70 | if (!nodeToRemove) 71 | { 72 | return NO; 73 | } 74 | 75 | [_nodes removeObject:nodeToRemove]; 76 | 77 | for (EDSGraphNode *n in _nodes) 78 | { 79 | long index = [n.neighbors indexOfObject:nodeToRemove]; 80 | if (index != -1) 81 | { 82 | [n.neighbors removeObjectAtIndex:index]; 83 | } 84 | } 85 | 86 | return YES; 87 | 88 | } 89 | -(void)addEdgeFromNode:(EDSGraphNode*)from toNode:(EDSGraphNode*)to 90 | { 91 | [from.neighbors addObject:to]; 92 | } 93 | 94 | -(void)addBidirectionalEdgeFromNode:(EDSGraphNode*)from toNode:(EDSGraphNode*)to 95 | { 96 | [from.neighbors addObject:to]; 97 | [to.neighbors addObject:from]; 98 | } 99 | 100 | -(BOOL)adjacent:(EDSGraphNode*)from toNode:(EDSGraphNode*)to 101 | { 102 | return [from.neighbors containsObject:to]; 103 | } 104 | 105 | -(NSMutableArray*)neighborsOfValue:(NSInteger)value 106 | { 107 | for (EDSGraphNode *n in _nodes) 108 | { 109 | if (n.value == value) 110 | { 111 | return n.neighbors; 112 | } 113 | } 114 | 115 | return nil; 116 | } 117 | 118 | @end 119 | -------------------------------------------------------------------------------- /Chapter11/Objective-C/EDSGraphNode.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSGraphNode.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/14/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSGraphNode : NSObject 12 | 13 | @property (nonatomic) NSInteger value; 14 | @property (nonatomic) NSMutableArray* neighbors; 15 | 16 | -(instancetype)initGraphNode; 17 | -(instancetype)initGraphNodeWithValue:(NSInteger)value; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /Chapter11/Objective-C/EDSGraphNode.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSGraphNode.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/14/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSGraphNode.h" 10 | 11 | @interface EDSGraphNode() 12 | { 13 | NSInteger _value; 14 | NSMutableArray *_neighbors; 15 | } 16 | 17 | @end 18 | 19 | 20 | @implementation EDSGraphNode 21 | 22 | -(instancetype)initGraphNode 23 | { 24 | if (self = [super init]) 25 | { 26 | _neighbors = [NSMutableArray array]; 27 | } 28 | 29 | return self; 30 | } 31 | 32 | -(instancetype)initGraphNodeWithValue:(NSInteger)value 33 | { 34 | if (self = [super init]) 35 | { 36 | _value = value; 37 | _neighbors = [NSMutableArray array]; 38 | } 39 | 40 | return self; 41 | } 42 | 43 | -(NSMutableArray*)neighbors 44 | { 45 | return _neighbors; 46 | } 47 | 48 | -(NSInteger)value 49 | { 50 | return _value; 51 | } 52 | 53 | @end 54 | -------------------------------------------------------------------------------- /Chapter11/Swift/Graph.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Graph.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 10/14/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public class Graph 12 | { 13 | public var nodes: Array = [GraphNode]() 14 | 15 | public init(nodes: Array) 16 | { 17 | self.nodes = nodes 18 | } 19 | 20 | public func count() -> Int 21 | { 22 | return nodes.count 23 | } 24 | 25 | public func addNode(node: GraphNode) 26 | { 27 | nodes.append(node) 28 | } 29 | 30 | public func addNodeForValue(value: Int) 31 | { 32 | let node = GraphNode(val: value) 33 | nodes.append(node); 34 | } 35 | 36 | public func removeNodeForValue(value: Int) -> Bool 37 | { 38 | var nodeToRemove: GraphNode? = nil 39 | 40 | for n in nodes 41 | { 42 | if (n.value == value) 43 | { 44 | nodeToRemove = n; 45 | break 46 | } 47 | } 48 | 49 | if (nodeToRemove == nil) 50 | { 51 | return false 52 | } 53 | 54 | if let index = nodes.index(of: nodeToRemove!) 55 | { 56 | nodes.remove(at: index) 57 | 58 | for n in nodes 59 | { 60 | if let foundIndex = n.neighbors.index(of: nodeToRemove!) 61 | { 62 | n.neighbors.remove(at: foundIndex) 63 | } 64 | } 65 | 66 | return true 67 | } 68 | 69 | return false 70 | 71 | } 72 | 73 | public func addEdgeFromNodeToNode(from: GraphNode, to: GraphNode) 74 | { 75 | from.neighbors.append(to) 76 | } 77 | 78 | public func addBidirectionalEdge(from: GraphNode, to: GraphNode) 79 | { 80 | from.neighbors.append(to) 81 | to.neighbors.append(from) 82 | } 83 | 84 | public func adjacent(from: GraphNode, to: GraphNode) -> Bool 85 | { 86 | if from.neighbors.index(of: to) != nil 87 | { 88 | return true 89 | } 90 | else 91 | { 92 | return false 93 | } 94 | } 95 | 96 | public func neighborsOfValue(value: Int) -> Array? 97 | { 98 | for n in nodes 99 | { 100 | if (n.value == value) 101 | { 102 | return n.neighbors 103 | } 104 | } 105 | 106 | return nil 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /Chapter11/Swift/GraphNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // GraphNode.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 10/14/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public class GraphNode : Equatable 12 | { 13 | public var neighbors: Array = [GraphNode]() 14 | public var value : Int 15 | 16 | public init(val: Int) { 17 | value = val 18 | } 19 | } 20 | 21 | public func == (lhs: GraphNode, rhs: GraphNode) -> Bool { 22 | return (lhs.value == rhs.value) 23 | } 24 | -------------------------------------------------------------------------------- /Chapter12/C#/ArraySortingAlgorithms.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EverydayDataStructures 5 | { 6 | public class ArraySortingAlgorithms 7 | { 8 | //int[] _values; 9 | 10 | public ArraySortingAlgorithms() 11 | { 12 | } 13 | 14 | void Swap(ref int x, ref int y) 15 | { 16 | int t = x; 17 | x = y; 18 | y = t; 19 | } 20 | 21 | //SelectionSort 22 | public void SelectionSort(int[] values) 23 | { 24 | if (values.Length <= 1) 25 | return; 26 | 27 | int j, minIndex; 28 | for (int i = 0; i < values.Length - 1; i++) 29 | { 30 | minIndex = i; 31 | for (j = i + 1; j < values.Length; j++) 32 | { 33 | if (values[j] < values[minIndex]) 34 | { 35 | minIndex = j; 36 | } 37 | } 38 | 39 | Swap(ref values[minIndex], ref values[i]); 40 | } 41 | } 42 | 43 | //InsertionSort 44 | public void InsertionSort(int[] values) 45 | { 46 | if (values.Length <= 1) 47 | return; 48 | 49 | int j, value; 50 | for (int i = 1; i < values.Length; i++) 51 | { 52 | value = values[i]; 53 | j = i - 1; 54 | 55 | while (j >= 0 && values[j] > value) 56 | { 57 | values[j + 1] = values[j]; 58 | j = j - 1; 59 | } 60 | values[j + 1] = value; 61 | } 62 | } 63 | 64 | //BubbleSort 65 | public void BubbleSort(int[] values) 66 | { 67 | bool swapped; 68 | for (int i = 0; i < values.Length - 1; i++) 69 | { 70 | swapped = false; 71 | for (int j = values.Length - 1; j > i; j--) 72 | { 73 | if (values[j] < values[j - 1]) 74 | { 75 | Swap(ref values[j], ref values[j - 1]); 76 | swapped = true; 77 | } 78 | } 79 | 80 | if (swapped == false) 81 | break; 82 | } 83 | } 84 | 85 | 86 | //QuickSort 87 | public void QuickSort(int[] values, int low, int high) 88 | { 89 | if (low < high) 90 | { 91 | int index = Partition(values, low, high); 92 | 93 | QuickSort(values, low, index - 1); 94 | QuickSort(values, index + 1, high); 95 | } 96 | } 97 | 98 | int Partition(int[] values, int low, int high) 99 | { 100 | int pivot = values[high]; 101 | int i = (low - 1); 102 | for (int j = low; j <= high - 1; j++) 103 | { 104 | if (values[j] <= pivot) 105 | { 106 | i++; 107 | 108 | Swap(ref values[i], ref values[j]); 109 | } 110 | } 111 | 112 | i++; 113 | Swap(ref values[i], ref values[high]); 114 | 115 | return i; 116 | } 117 | 118 | //MergeSort 119 | public void MergeSort(int[] values, int left, int right) 120 | { 121 | if (left == right) 122 | return; 123 | 124 | if (left < right) 125 | { 126 | int middle = (left + right) / 2; 127 | 128 | MergeSort(values, left, middle); 129 | MergeSort(values, middle + 1, right); 130 | 131 | int[] temp = new int[values.Length]; 132 | for (int n = left; n <= right; n++) 133 | { 134 | temp[n] = values[n]; 135 | } 136 | 137 | int index1 = left; 138 | int index2 = middle + 1; 139 | for (int n = left; n <= right; n++) 140 | { 141 | if (index1 == middle + 1) 142 | { 143 | values[n] = temp[index2++]; 144 | } 145 | else if (index2 > right) 146 | { 147 | values[n] = temp[index1++]; 148 | } 149 | else if (temp[index1] < temp[index2]) 150 | { 151 | values[n] = temp[index1++]; 152 | } 153 | else 154 | { 155 | values[n] = temp[index2++]; 156 | } 157 | } 158 | } 159 | } 160 | 161 | //BucketSort 162 | public void BucketSort(int[] values, int maxVal) 163 | { 164 | int[] bucket = new int[maxVal + 1]; 165 | int num = values.Length; 166 | int bucketNum = bucket.Length; 167 | 168 | for (int i = 0; i < bucketNum; i++) 169 | { 170 | bucket[i] = 0; 171 | } 172 | 173 | for (int i = 0; i < num; i++) 174 | { 175 | bucket[values[i]]++; 176 | } 177 | 178 | int pos = 0; 179 | for (int i = 0; i < bucketNum; i++) 180 | { 181 | for (int j = 0; j < bucket[i]; j++) 182 | { 183 | values[pos++] = i; 184 | } 185 | } 186 | } 187 | 188 | //CountingSort 189 | public void CountingSort(int[] values) 190 | { 191 | int n = values.Length; 192 | int min = values[0]; 193 | int max = values[0]; 194 | for (int i = 1; i < n; i++) 195 | { 196 | if (values[i] < min) 197 | { 198 | min = values[i]; 199 | } 200 | else if (values[i] > max) 201 | { 202 | max = values[i]; 203 | } 204 | } 205 | 206 | int[] count = new int[max - min + 1]; 207 | int z = 0; 208 | 209 | for (int i = 0; i < n; i++) 210 | { 211 | count[i] = 0; 212 | } 213 | 214 | for (int i = 0; i < n; i++) 215 | { 216 | count[values[i] - min]++; 217 | } 218 | 219 | for (int i = min; i <= max; i++) 220 | { 221 | while (count[i - min]-- > 0) 222 | { 223 | values[z] = i; 224 | ++z; 225 | } 226 | } 227 | } 228 | 229 | //RadixSort 230 | public void RadixSort(int[] values) 231 | { 232 | int n = values.Length; 233 | int max = values[0]; 234 | for (int i = 1; i < n; i++) 235 | { 236 | if (values[i] > max) 237 | { 238 | max = values[i]; 239 | } 240 | } 241 | 242 | for (int exp = 1; max / exp > 0; exp *= 10) 243 | { 244 | int[] output = new int[n]; 245 | int[] count = new int[10]; 246 | 247 | // Store count of occurrences in count[] 248 | for (int i = 0; i < n; i++) 249 | { 250 | count[(values[i] / exp) % 10]++; 251 | } 252 | 253 | for (int i = 1; i < 10; i++) 254 | { 255 | count[i] += count[i - 1]; 256 | } 257 | 258 | for (int i = n - 1; i >= 0; i--) 259 | { 260 | output[count[(values[i] / exp) % 10] - 1] = values[i]; 261 | count[(values[i] / exp) % 10]--; 262 | } 263 | 264 | for (int i = 0; i < n; i++) 265 | { 266 | values[i] = output[i]; 267 | } 268 | } 269 | } 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /Chapter12/Java/ArraySortingAlgorithms.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /** 4 | * Created by William Smith on 10/26/16. 5 | */ 6 | public class ArraySortingAlgorithms 7 | { 8 | //InsertionSort 9 | public void insertionSort(int[] values) 10 | { 11 | if (values.length <= 1) 12 | return; 13 | 14 | int j, value; 15 | for (int i = 1; i < values.length; i++) 16 | { 17 | value = values[i]; 18 | j = i - 1; 19 | 20 | while (j >= 0 && values[j] > value) 21 | { 22 | values[j + 1] = values[j]; 23 | j = j - 1; 24 | } 25 | values[j + 1] = value; 26 | } 27 | } 28 | 29 | //SelectionSort 30 | public void selectionSort(int[] values) 31 | { 32 | if (values.length <= 1) 33 | return; 34 | 35 | int j, minIndex; 36 | for (int i = 0; i < values.length - 1; i++) 37 | { 38 | minIndex = i; 39 | for (j = i + 1; j < values.length; j++) 40 | { 41 | if (values[j] < values[minIndex]) 42 | { 43 | minIndex = j; 44 | } 45 | } 46 | 47 | int temp = values[minIndex]; 48 | values[minIndex] = values[i]; 49 | values[i] = temp; 50 | } 51 | } 52 | 53 | //MergeSort 54 | public void mergeSort(int[] values, int left, int right) 55 | { 56 | if (left == right) 57 | return; 58 | 59 | if (left < right) { 60 | int middle = (left + right) / 2; 61 | 62 | mergeSort(values, left, middle); 63 | mergeSort(values, middle + 1, right); 64 | 65 | int[] temp = new int[values.length]; 66 | for (int n = left; n <= right; n++) { 67 | temp[n] = values[n]; 68 | } 69 | 70 | int index1 = left; 71 | int index2 = middle + 1; 72 | for (int n = left; n <= right; n++) { 73 | if (index1 == middle + 1) { 74 | values[n] = temp[index2++]; 75 | } else if (index2 > right) { 76 | values[n] = temp[index1++]; 77 | } else if (temp[index1] < temp[index2]) { 78 | values[n] = temp[index1++]; 79 | } else { 80 | values[n] = temp[index2++]; 81 | } 82 | } 83 | } 84 | } 85 | 86 | //QuickSort 87 | public void quickSort(int[] values, int low, int high) 88 | { 89 | if (low < high) 90 | { 91 | int index = partition(values, low, high); 92 | 93 | quickSort(values, low, index - 1); 94 | quickSort(values, index + 1, high); 95 | } 96 | } 97 | 98 | int partition(int[] values, int low, int high) 99 | { 100 | int pivot = values[high]; 101 | int i = (low - 1); 102 | for (int j = low; j <= high - 1; j++) 103 | { 104 | if (values[j] <= pivot) 105 | { 106 | i++; 107 | 108 | int temp = values[i]; 109 | values[i] = values[j]; 110 | values[j] = temp; 111 | } 112 | } 113 | 114 | i++; 115 | int temp = values[i]; 116 | values[i] = values[high]; 117 | values[high] = temp; 118 | 119 | return i; 120 | } 121 | 122 | //BubbleSort 123 | public void bubbleSort(int[] values) 124 | { 125 | boolean swapped; 126 | for (int i = 0; i < values.length - 1; i++) 127 | { 128 | swapped = false; 129 | for (int j = values.length -1; j > i; j--) 130 | { 131 | if (values[j] < values[j - 1]) 132 | { 133 | int temp = values[j]; 134 | values[j] = values[j - 1]; 135 | values[j - 1] = temp; 136 | swapped = true; 137 | } 138 | } 139 | 140 | if (swapped == false) 141 | break; 142 | } 143 | } 144 | 145 | //BucketSort 146 | public void BucketSort(int[] values, int maxVal) 147 | { 148 | int[] bucket = new int[maxVal + 1]; 149 | int num = values.length; 150 | int bucketNum = bucket.length; 151 | 152 | for (int i = 0; i < bucketNum; i++) 153 | { 154 | bucket[i] = 0; 155 | } 156 | 157 | for (int i = 0; i < num; i++) 158 | { 159 | bucket[values[i]]++; 160 | } 161 | 162 | int pos = 0; 163 | for (int i = 0; i < bucketNum; i++) 164 | { 165 | for (int j = 0; j < bucket[i]; j++) 166 | { 167 | values[pos++] = i; 168 | } 169 | } 170 | } 171 | 172 | //CountingSort 173 | public void CountingSort(int[] values) 174 | { 175 | int n = values.length; 176 | int min = values[0]; 177 | int max = values[0]; 178 | for (int i = 1; i < n; i++) 179 | { 180 | if (values[i] < min) 181 | { 182 | min = values[i]; 183 | } 184 | else if (values[i] > max) 185 | { 186 | max = values[i]; 187 | } 188 | } 189 | 190 | int[] count = new int[max - min + 1]; 191 | int z = 0; 192 | 193 | for (int i = 0; i < n; i++) 194 | { 195 | count[i] = 0; 196 | } 197 | 198 | for (int i = 0; i < n; i++) 199 | { 200 | count[values[i] - min]++; 201 | } 202 | 203 | for (int i = min; i <= max; i++) 204 | { 205 | while (count[i - min]-- > 0) 206 | { 207 | values[z] = i; 208 | ++z; 209 | } 210 | } 211 | } 212 | 213 | //RadixSort 214 | public void RadixSort(int[] values) 215 | { 216 | int n = values.length; 217 | int max = values[0]; 218 | for (int i = 1; i < n; i++) 219 | { 220 | if (values[i] > max) 221 | { 222 | max = values[i]; 223 | } 224 | } 225 | 226 | for (int exp = 1; max / exp > 0; exp *= 10) 227 | { 228 | int[] output = new int[n]; 229 | int[] count = new int[10]; 230 | 231 | // Store count of occurrences in count[] 232 | for (int i = 0; i < n; i++) 233 | { 234 | count[(values[i] / exp) % 10]++; 235 | } 236 | 237 | for (int i = 1; i < 10; i++) 238 | { 239 | count[i] += count[i - 1]; 240 | } 241 | 242 | for (int i = n - 1; i >= 0; i--) 243 | { 244 | output[count[(values[i] / exp) % 10] - 1] = values[i]; 245 | count[(values[i] / exp) % 10]--; 246 | } 247 | 248 | for (int i = 0; i < n; i++) 249 | { 250 | values[i] = output[i]; 251 | } 252 | } 253 | } 254 | 255 | 256 | } 257 | -------------------------------------------------------------------------------- /Chapter12/Java/main.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | * To change this license header, choose License Headers in Project Properties. 5 | * To change this template file, choose Tools | Templates 6 | * and open the template in the editor. 7 | */ 8 | 9 | import main.java.*; 10 | 11 | /** 12 | * 13 | * @author William Smith 14 | */ 15 | public class main { 16 | 17 | /** 18 | * @param args the command line arguments 19 | */ 20 | public static void main(String[] args) { 21 | 22 | System.out.println("Hello, World!"); 23 | // IntegerTypes.intDemo(); 24 | // FloatTypes.floatDemo(); 25 | // BooleanType.boolDemo(); 26 | // StringType.stringDemo(); 27 | // User u1 = new User("Will", 1); 28 | // User u2 = new User("Bob", 2); 29 | // User u3 = new User("Joe", 3); 30 | // User u4 = new User("Ron", 4); 31 | // User u5 = new User("Dorothy", 5); 32 | // LoggedInUserArray array = new LoggedInUserArray(); 33 | // 34 | // array.UserAuthenticated(u1); 35 | // array.UserAuthenticated(u2); 36 | // array.UserAuthenticated(u3); 37 | // array.UserAuthenticated(u4); 38 | // 39 | // array.UserLoggedOut(u4); 40 | // array.UserAuthenticated(u5); 41 | 42 | int[] arr = {12, 11, 13, 5, 6, 9, 18, 110, 3, 14, 27, 8, 12, 0}; 43 | 44 | ArraySortingAlgorithms algo = new ArraySortingAlgorithms(); 45 | // algo.insertionSort(arr); 46 | // algo.selectionSort(arr); 47 | // algo.mergeSort(arr, 0, arr.length - 1); 48 | // algo.quickSort(arr, 0, arr.length - 1); 49 | // algo.bubbleSort(arr); 50 | // algo.BucketSort(arr, 110); 51 | // algo.CountingSort(arr); 52 | // algo.RadixSort(arr); 53 | 54 | for (int i : arr) 55 | { 56 | System.out.println(i); 57 | } 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Chapter12/Objective-C/EDSArraySortingAlgorithms.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSArraySortingAlgorithms.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/26/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EDSArraySortingAlgorithms : NSObject 12 | 13 | -(void)selectionSortArray:(NSMutableArray*)values; 14 | -(void)insertionSortArray:(NSMutableArray*)values; 15 | -(void)bubbleSortArray:(NSMutableArray*)values; 16 | -(void)quickSortArray:(NSMutableArray*)values 17 | forLowIndex:(NSInteger)low 18 | andHighIndex:(NSInteger)high; 19 | -(void)mergeSortArray:(NSMutableArray*)array 20 | withLeftIndex:(NSInteger)left 21 | andRightIndex:(NSInteger)right; 22 | -(void)bucketSortArray:(NSMutableArray*)values 23 | withMaxValue:(NSInteger)maxValue; 24 | -(void)countingSortArray:(NSMutableArray*)values; 25 | -(void)radixSortArray:(NSMutableArray*)values; 26 | 27 | -(void) csort:(NSMutableArray*)values; 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /Chapter12/Objective-C/EDSArraySortingAlgorithms.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSArraySortingAlgorithms.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/26/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSArraySortingAlgorithms.h" 10 | 11 | @implementation EDSArraySortingAlgorithms 12 | 13 | //SelectionSort 14 | -(void)selectionSortArray:(NSMutableArray*)values 15 | { 16 | if ([values count] <= 1) 17 | return; 18 | 19 | NSInteger j, minIndex; 20 | for (int i = 0; i < [values count] - 1; i++) 21 | { 22 | minIndex = i; 23 | for (j = i + 1; j < [values count]; j++) 24 | { 25 | if ([values[j] intValue] < [values[minIndex] intValue]) 26 | { 27 | minIndex = j; 28 | } 29 | } 30 | 31 | NSNumber *temp = (NSNumber*)values[minIndex]; 32 | values[minIndex] = values[i]; 33 | values[i] = temp; 34 | } 35 | } 36 | 37 | //InsertionSort 38 | -(void)insertionSortArray:(NSMutableArray*)values 39 | { 40 | if ([values count] <= 1) 41 | return; 42 | 43 | NSInteger j, value; 44 | for (int i = 1; i < [values count]; i++) 45 | { 46 | value = [values[i] intValue]; 47 | j = i - 1; 48 | 49 | while (j >= 0 && [values[j] intValue] > value) 50 | { 51 | values[j + 1] = values[j]; 52 | j = j - 1; 53 | } 54 | values[j + 1] = [NSNumber numberWithInteger:value]; 55 | } 56 | } 57 | 58 | //BubbleSort 59 | -(void)bubbleSortArray:(NSMutableArray*)values 60 | { 61 | bool swapped; 62 | for (NSInteger i = 0; i < [values count] - 1; i++) 63 | { 64 | swapped = false; 65 | for (NSInteger j = [values count] - 1; j > i; j--) 66 | { 67 | if (values[j] < values[j - 1]) 68 | { 69 | NSInteger temp = [values[j] intValue]; 70 | values[j] = values[j - 1]; 71 | values[j - 1] = [NSNumber numberWithInteger:temp]; 72 | swapped = true; 73 | } 74 | } 75 | 76 | if (swapped == false) 77 | break; 78 | } 79 | } 80 | 81 | //QuickSort 82 | -(void)quickSortArray:(NSMutableArray*)values 83 | forLowIndex:(NSInteger)low 84 | andHighIndex:(NSInteger)high 85 | { 86 | if (low < high) 87 | { 88 | NSInteger index = [self partitionArray:values 89 | forLowIndex:low 90 | andHighIndex:high]; 91 | 92 | [self quickSortArray:values 93 | forLowIndex:low 94 | andHighIndex:index - 1]; 95 | [self quickSortArray:values 96 | forLowIndex:index + 1 97 | andHighIndex:high]; 98 | } 99 | } 100 | 101 | -(NSInteger)partitionArray:(NSMutableArray*)values 102 | forLowIndex:(NSInteger)low 103 | andHighIndex:(NSInteger)high 104 | { 105 | NSInteger pivot = [values[high] intValue]; 106 | NSInteger i = (low - 1); 107 | for (NSInteger j = low; j <= high - 1; j++) 108 | { 109 | if ([values[j] intValue] <= pivot) 110 | { 111 | i++; 112 | 113 | NSInteger temp = [values[i] intValue]; 114 | values[i] = values[j]; 115 | values[j] = [NSNumber numberWithInteger:temp]; 116 | } 117 | } 118 | 119 | i++; 120 | NSInteger temp = [values[i] intValue]; 121 | values[i] = values[high]; 122 | values[high] = [NSNumber numberWithInteger:temp]; 123 | 124 | return i; 125 | } 126 | 127 | //MergeSort 128 | -(void)mergeSortArray:(NSMutableArray*)values 129 | withLeftIndex:(NSInteger)left 130 | andRightIndex:(NSInteger)right 131 | { 132 | if (left == right) 133 | return; 134 | 135 | if (left < right) 136 | { 137 | NSInteger middle = (left + right) / 2; 138 | 139 | [self mergeSortArray:values 140 | withLeftIndex:left 141 | andRightIndex:middle]; 142 | 143 | [self mergeSortArray:values 144 | withLeftIndex:middle + 1 145 | andRightIndex:right]; 146 | 147 | NSMutableArray *temp = [NSMutableArray arrayWithArray:values]; 148 | 149 | NSInteger index1 = left; 150 | NSInteger index2 = middle + 1; 151 | for (NSInteger n = left; n <= right; n++) 152 | { 153 | if (index1 == middle + 1) 154 | { 155 | values[n] = temp[index2++]; 156 | } 157 | else if (index2 > right) 158 | { 159 | values[n] = temp[index1++]; 160 | } 161 | else if (temp[index1] < temp[index2]) 162 | { 163 | values[n] = temp[index1++]; 164 | } 165 | else 166 | { 167 | values[n] = temp[index2++]; 168 | } 169 | } 170 | } 171 | } 172 | 173 | //BucketSort 174 | -(void)bucketSortArray:(NSMutableArray*)values 175 | withMaxValue:(NSInteger)maxValue 176 | { 177 | NSMutableArray*bucket = [NSMutableArray array]; 178 | NSInteger num = [values count]; 179 | NSInteger bucketNum = maxValue + 1; 180 | 181 | for (int i = 0; i < bucketNum; i++) 182 | { 183 | [bucket insertObject:[NSNumber numberWithInteger:0] atIndex:i]; 184 | } 185 | 186 | for (int i = 0; i < num; i++) 187 | { 188 | NSInteger value = [bucket[[values[i] intValue]] intValue] + 1; 189 | bucket[[values[i] intValue]] = [NSNumber numberWithInteger:value]; 190 | } 191 | 192 | int pos = 0; 193 | 194 | for (int i = 0; i < bucketNum; i++) 195 | { 196 | for (int j = 0; j < [bucket[i] intValue]; j++) 197 | { 198 | values[pos++] = [NSNumber numberWithInteger:i]; 199 | } 200 | } 201 | } 202 | 203 | //CountingSort 204 | -(void)countingSortArray:(NSMutableArray*)values 205 | { 206 | int n = (int)[values count]; 207 | int min = [values[0] intValue]; 208 | int max = [values[0] intValue]; 209 | for (int i = 1; i < n; i++) 210 | { 211 | int iVal = (int)[values[i] intValue]; 212 | if (iVal < min) 213 | { 214 | min = iVal; 215 | } 216 | else if (iVal > max) 217 | { 218 | max = iVal; 219 | } 220 | } 221 | 222 | NSMutableArray *count = [NSMutableArray array]; 223 | for (int i = 0; i < max; i++) 224 | { 225 | count[i] = [NSNumber numberWithInteger:0]; 226 | } 227 | 228 | for (int i = 0; i < n; i++) 229 | { 230 | //count[values[i] - min]++; 231 | int countIndex = [values[i] intValue] - min; 232 | int newValue = [count[countIndex] intValue] + 1; 233 | count[countIndex] = [NSNumber numberWithInteger:newValue]; 234 | } 235 | 236 | int z = 0; 237 | for (int i = min; i <= max; i++) 238 | { 239 | while ([count[i - min] intValue] > 0) 240 | { 241 | values[z] = [NSNumber numberWithInteger:i]; 242 | ++z; 243 | 244 | NSNumber *num = [NSNumber numberWithInteger:([count[i - min] intValue] - 1)]; 245 | count[i - min] = num; 246 | } 247 | } 248 | } 249 | 250 | //RadixSort 251 | -(void)radixSortArray:(NSMutableArray*)values 252 | { 253 | NSInteger n = [values count]; 254 | NSInteger max = [values[0] intValue]; 255 | for (int i = 1; i < n; i++) 256 | { 257 | if ([values[i] intValue] > max) 258 | { 259 | max = [values[i] intValue]; 260 | } 261 | } 262 | 263 | for (int exp = 1; max / exp > 0; exp *= 10) 264 | { 265 | NSMutableArray *output = [NSMutableArray array]; 266 | for (int i = 0; i < n; i++) 267 | { 268 | [output addObject:[NSNumber numberWithInteger:0]]; 269 | } 270 | 271 | NSMutableArray *count = [NSMutableArray array]; 272 | for (int i = 0; i < 10; i++) 273 | { 274 | [count addObject:[NSNumber numberWithInteger:0]]; 275 | } 276 | 277 | for (int i = 0; i < n; i++) 278 | { 279 | NSInteger index = ([values[i] intValue] / exp) % 10; 280 | NSInteger newValue = [count[index] intValue] + 1; 281 | count[index] = [NSNumber numberWithInteger:newValue]; 282 | } 283 | 284 | for (int i = 1; i < 10; i++) 285 | { 286 | NSInteger newValue = [count[i] intValue] + [count[i - 1] intValue]; 287 | count[i] = [NSNumber numberWithInteger:newValue]; 288 | } 289 | 290 | for (NSInteger i = n - 1; i >= 0; i--) 291 | { 292 | NSInteger countIndex = (([values[i] intValue] / exp) % 10); 293 | NSInteger outputIndex = [count[countIndex] intValue] - 1; 294 | output[outputIndex] = values[i]; 295 | 296 | NSInteger countValue = [count[countIndex] intValue] - 1; 297 | count[countIndex] = [NSNumber numberWithInteger:countValue]; 298 | } 299 | 300 | for (int i = 0; i < n; i++) 301 | { 302 | values[i] = output[i]; 303 | } 304 | } 305 | } 306 | 307 | @end 308 | -------------------------------------------------------------------------------- /Chapter12/Objective-C/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/4/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "EDSIntegerTypes.h" 11 | #import "EDSFloatingTypes.h" 12 | #import "EDSBooleanType.h" 13 | #import "EDSStringType.h" 14 | #import "EDSLoggedInUserArray.h" 15 | #import "EDSUser.h" 16 | #import "EDSCollectionTests.h" 17 | 18 | #import "EDSArraySortingAlgorithms.h" 19 | 20 | int main(int argc, const char * argv[]) { 21 | @autoreleasepool { 22 | NSMutableArray *arr = [NSMutableArray arrayWithObjects:[NSNumber numberWithInteger:12], [NSNumber numberWithInteger:11], [NSNumber numberWithInteger:13], [NSNumber numberWithInteger:5], [NSNumber numberWithInteger:6], [NSNumber numberWithInteger:9], [NSNumber numberWithInteger:18], [NSNumber numberWithInteger:110], [NSNumber numberWithInteger:3], [NSNumber numberWithInteger:14], [NSNumber numberWithInteger:27], [NSNumber numberWithInteger:27], [NSNumber numberWithInteger:0], nil]; 23 | 24 | EDSArraySortingAlgorithms *algo = [[EDSArraySortingAlgorithms alloc] init]; 25 | 26 | // [algo selectionSortArray:arr]; 27 | // [algo insertionSortArray:arr]; 28 | // [algo bubbleSortArray:arr]; 29 | // [algo quickSortArray:arr forLowIndex:0 andHighIndex:arr.count - 1]; 30 | // [algo mergeSortArray:arr withLeftIndex:0 andRightIndex:arr.count - 1]; 31 | // [algo bucketSortArray:arr withMaxValue:110]; 32 | // [algo countingSortArray:arr]; 33 | [algo radixSortArray:arr]; 34 | 35 | for (NSNumber *num in arr) { 36 | NSLog(@"%li", (long)[num integerValue]); 37 | } 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Chapter12/Swift/ArraySortingAlgorithms.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ArraySortingAlgorithms.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 10/26/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | public class ArraySortingAlgorithms 12 | { 13 | open func swap( x: inout Int, y: inout Int) 14 | { 15 | let t: Int = x 16 | x = y 17 | y = t 18 | } 19 | 20 | //Insertion Sort 21 | open func insertionSort( values: inout [Int]) 22 | { 23 | if (values.count <= 1) 24 | { 25 | return 26 | } 27 | 28 | var j, value: Int 29 | for i in 1..= 0 && values[j] > value) 35 | { 36 | values[j + 1] = values[j] 37 | j = j - 1 38 | } 39 | values[j + 1] = value 40 | } 41 | } 42 | 43 | //Selection Sort 44 | open func selectionSort( values: inout [Int]) 45 | { 46 | if (values.count <= 1) 47 | { 48 | return 49 | } 50 | 51 | var minIndex: Int 52 | for i in 0.. Int 80 | { 81 | let pivot: Int = values[high] 82 | var i: Int = (low - 1) 83 | var j: Int = low 84 | 85 | while j <= (high - 1) 86 | { 87 | if (values[j] <= pivot) 88 | { 89 | i += 1 90 | swap(x: &values[i], y: &values[j]) 91 | } 92 | 93 | j += 1 94 | } 95 | 96 | i += 1 97 | swap(x: &values[i], y: &values[high]) 98 | 99 | return i; 100 | } 101 | 102 | 103 | //Merge Sort 104 | open func mergeSort( values: inout [Int], left: Int, right: Int) 105 | { 106 | if (left == right) 107 | { 108 | return 109 | } 110 | 111 | if (left < right) 112 | { 113 | let middle: Int = (left + right) / 2 114 | 115 | mergeSort(values: &values, left: left, right: middle) 116 | mergeSort(values: &values, left: middle + 1, right: right) 117 | 118 | var temp = values 119 | 120 | var index1: Int = left 121 | var index2: Int = middle + 1 122 | for n in left...right 123 | { 124 | if (index1 == middle + 1) 125 | { 126 | values[n] = temp[index2] 127 | index2 += 1 128 | } 129 | else if (index2 > right) 130 | { 131 | values[n] = temp[index1] 132 | index1 += 1 133 | } 134 | else if (temp[index1] < temp[index2]) 135 | { 136 | values[n] = temp[index1] 137 | index1 += 1 138 | } 139 | else 140 | { 141 | values[n] = temp[index2] 142 | index2 += 1 143 | } 144 | } 145 | } 146 | } 147 | 148 | //BubbleSort 149 | open func bubbleSort( values: inout [Int]) 150 | { 151 | if (values.count <= 1) 152 | { 153 | return 154 | } 155 | 156 | var swapped: Bool 157 | var i: Int = 0 158 | while i < (values.count - 1) 159 | { 160 | swapped = false 161 | var j: Int = values.count - 1 162 | while j > i 163 | { 164 | if (values[j] < values[j - 1]) 165 | { 166 | swap(x: &values[j], y: &values[j - 1]) 167 | swapped = true 168 | } 169 | j -= 1 170 | } 171 | 172 | if (swapped == false) 173 | { 174 | break 175 | } 176 | i += 1 177 | } 178 | } 179 | 180 | //BucketSort 181 | open func bucketSort( values: inout [Int], maxVal: Int) 182 | { 183 | var bucket = [Int]() 184 | let num: Int = values.count 185 | let bucketNum: Int = maxVal + 1 186 | 187 | for i in 0.. max) 223 | { 224 | max = iVal 225 | } 226 | } 227 | 228 | var count = [Int]() 229 | for i in 0.. 0) 244 | { 245 | values[z] = i 246 | z += 1 247 | count[i - min] = count[i - min] - 1 248 | } 249 | i += 1 250 | } 251 | } 252 | 253 | 254 | //RadixSort 255 | open func radixSort( values: inout [Int]) 256 | { 257 | let n: Int = values.count 258 | var max: Int = values[0] 259 | 260 | for i in 1.. max) 263 | { 264 | max = values[i]; 265 | } 266 | } 267 | 268 | var exp: Int = 1 269 | while max/exp > 0 { 270 | var output: [Int] = [Int]() 271 | for _ in 0..= 0 295 | { 296 | let index: Int = (values[i] / exp) % 10 297 | output[count[index] - 1] = values[i] 298 | count[index] = count[index] - 1 299 | i -= 1 300 | } 301 | 302 | for i in 0..= left) 41 | { 42 | int mid = left + (right - left) / 2; 43 | 44 | if (values[mid] == key) 45 | { 46 | return mid; 47 | } 48 | else if (values[mid] > key) 49 | { 50 | return BinarySearch(values, left, mid - 1, key); 51 | } 52 | 53 | return BinarySearch(values, mid + 1, right, key); 54 | } 55 | 56 | return -1; 57 | } 58 | 59 | //Jump Search 60 | public int JumpSearch(int[] values, int key) 61 | { 62 | int n = values.Length; 63 | int step = (int)Math.Sqrt(n); 64 | int prev = 0; 65 | 66 | while (values[Math.Min(step, n) - 1] < key) 67 | { 68 | prev = step; 69 | step += (int)Math.Floor(Math.Sqrt(n)); 70 | if (prev >= n) 71 | { 72 | return -1; 73 | } 74 | } 75 | 76 | while (values[prev] < key) 77 | { 78 | prev++; 79 | if (prev == Math.Min(step, n)) 80 | { 81 | return -1; 82 | } 83 | } 84 | 85 | if (values[prev] == key) 86 | { 87 | return prev; 88 | } 89 | 90 | return -1; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Chapter13/Java/ArraySearchAlgorithms.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | /** 4 | * Created by William Smith on 10/31/16. 5 | */ 6 | public class ArraySearchAlgorithms 7 | { 8 | //Linear Search 9 | public int linearSearchIndex(int[] values, int key) 10 | { 11 | for (int i = 0; i < values.length - 1; i++) 12 | { 13 | if (values[i] == key) 14 | { 15 | return i; 16 | } 17 | } 18 | 19 | return -1; 20 | } 21 | 22 | public Customer linearSearchCustomer(Customer[] customers, int custId) 23 | { 24 | for (int i = 0; i < customers.length - 1; i++) 25 | { 26 | if (customers[i].customerId == custId) 27 | { 28 | return customers[i]; 29 | } 30 | } 31 | 32 | return null; 33 | } 34 | 35 | //Binary Search 36 | public int binarySearch(int[] values, int left, int right, int key) 37 | { 38 | if (right >= left) 39 | { 40 | int mid = left + (right - left) / 2; 41 | 42 | if (values[mid] == key) 43 | { 44 | return mid; 45 | } 46 | else if (values[mid] > key) 47 | { 48 | return binarySearch(values, left, mid - 1, key); 49 | } 50 | 51 | return binarySearch(values, mid + 1, right, key); 52 | } 53 | 54 | return -1; 55 | } 56 | 57 | //Jump Search 58 | public int jumpSearch(int[] values, int key) 59 | { 60 | int n = values.length; 61 | int step = (int)Math.sqrt(n); 62 | int prev = 0; 63 | 64 | while (values[Math.min(step, n) - 1] < key) 65 | { 66 | prev = step; 67 | step += (int)Math.floor(Math.sqrt(n)); 68 | if (prev >= n) 69 | { 70 | return -1; 71 | } 72 | } 73 | 74 | while (values[prev] < key) 75 | { 76 | prev++; 77 | if (prev == Math.min(step, n)) 78 | { 79 | return -1; 80 | } 81 | } 82 | 83 | if (values[prev] == key) 84 | { 85 | return prev; 86 | } 87 | 88 | return -1; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /Chapter13/Java/main.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | * To change this license header, choose License Headers in Project Properties. 5 | * To change this template file, choose Tools | Templates 6 | * and open the template in the editor. 7 | */ 8 | 9 | import main.java.*; 10 | 11 | /** 12 | * 13 | * @author William Smith 14 | */ 15 | public class main { 16 | 17 | /** 18 | * @param args the command line arguments 19 | */ 20 | public static void main(String[] args) { 21 | 22 | System.out.println("Hello, World!"); 23 | // IntegerTypes.intDemo(); 24 | // FloatTypes.floatDemo(); 25 | // BooleanType.boolDemo(); 26 | // StringType.stringDemo(); 27 | // User u1 = new User("Will", 1); 28 | // User u2 = new User("Bob", 2); 29 | // User u3 = new User("Joe", 3); 30 | // User u4 = new User("Ron", 4); 31 | // User u5 = new User("Dorothy", 5); 32 | // LoggedInUserArray array = new LoggedInUserArray(); 33 | // 34 | // array.UserAuthenticated(u1); 35 | // array.UserAuthenticated(u2); 36 | // array.UserAuthenticated(u3); 37 | // array.UserAuthenticated(u4); 38 | // 39 | // array.UserLoggedOut(u4); 40 | // array.UserAuthenticated(u5); 41 | 42 | int[] arr = {12, 11, 13, 5, 6, 9, 18, 110, 3, 14, 27, 8, 12, 0}; 43 | 44 | ArraySortingAlgorithms algo = new ArraySortingAlgorithms(); 45 | // algo.insertionSort(arr); 46 | // algo.selectionSort(arr); 47 | // algo.mergeSort(arr, 0, arr.length - 1); 48 | // algo.quickSort(arr, 0, arr.length - 1); 49 | // algo.bubbleSort(arr); 50 | // algo.BucketSort(arr, 110); 51 | // algo.CountingSort(arr); 52 | // algo.RadixSort(arr); 53 | 54 | for (int i : arr) 55 | { 56 | System.out.println(i); 57 | } 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Chapter13/Objective-C/EDSArraySearchAlgorithms.h: -------------------------------------------------------------------------------- 1 | // 2 | // EDSArraySearchAlgorithms.h 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/31/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class EDSCustomer; 12 | 13 | @interface EDSArraySearchAlgorithms : NSObject 14 | 15 | -(NSInteger)linearSearchArray:(NSMutableArray*)values 16 | byKey:(NSInteger)key; 17 | 18 | -(EDSCustomer*)linearSearchCustomers:(NSMutableArray*)customers 19 | byCustId:(NSInteger)custId; 20 | 21 | -(NSInteger)binarySearchArray:(NSMutableArray*)values 22 | withLeftIndex:(NSInteger)left 23 | rightIndex:(NSInteger)right 24 | andKey:(NSInteger)key; 25 | 26 | -(NSInteger)jumpSearchArray:(NSMutableArray*)values 27 | forKey:(NSInteger)key; 28 | @end 29 | -------------------------------------------------------------------------------- /Chapter13/Objective-C/EDSArraySearchAlgorithms.m: -------------------------------------------------------------------------------- 1 | // 2 | // EDSArraySearchAlgorithms.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 10/31/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import "EDSArraySearchAlgorithms.h" 10 | #import "EDSCustomer.h" 11 | #import "math.h" 12 | 13 | 14 | @implementation EDSArraySearchAlgorithms 15 | 16 | //Sequential / Linear 17 | -(NSInteger)linearSearchArray:(NSMutableArray*)values 18 | byKey:(NSInteger)key 19 | { 20 | for (int i = 0; i < [values count] - 1; i++) 21 | { 22 | if ([values[i] intValue] == key) 23 | { 24 | return i; 25 | } 26 | } 27 | 28 | return -1; 29 | } 30 | 31 | -(EDSCustomer*)linearSearchCustomers:(NSMutableArray*)customers 32 | byCustId:(NSInteger)custId 33 | { 34 | for (EDSCustomer *c in customers) { 35 | 36 | if (c.customerId == custId) 37 | { 38 | return c; 39 | } 40 | } 41 | 42 | return nil; 43 | } 44 | 45 | //Binary Search 46 | -(NSInteger)binarySearchArray:(NSMutableArray*)values 47 | withLeftIndex:(NSInteger)left 48 | rightIndex:(NSInteger)right 49 | andKey:(NSInteger)key 50 | { 51 | if (right >= left) 52 | { 53 | NSInteger mid = left + (right - left) / 2; 54 | 55 | if ([values[mid] intValue] == key) 56 | { 57 | return mid; 58 | } 59 | else if ([values[mid] intValue] > key) 60 | { 61 | return [self binarySearchArray:values withLeftIndex:left rightIndex:mid - 1 andKey:key]; 62 | } 63 | 64 | return [self binarySearchArray:values withLeftIndex:mid + 1 rightIndex:right andKey:key]; 65 | } 66 | 67 | return -1; 68 | } 69 | 70 | //Jump Search 71 | -(NSInteger)jumpSearchArray:(NSMutableArray*)values 72 | forKey:(NSInteger)key 73 | { 74 | NSInteger n = [values count]; 75 | NSInteger step = sqrt(n); 76 | 77 | NSInteger prev = 0; 78 | while ([values[(int)fmin(step, n)-1] intValue] < key) 79 | { 80 | prev = step; 81 | step += floor(sqrt(n)); 82 | if (prev >= n) 83 | { 84 | return -1; 85 | } 86 | } 87 | 88 | while ([values[prev] intValue] < key) 89 | { 90 | prev++; 91 | if (prev == fmin(step, n)) 92 | { 93 | return -1; 94 | } 95 | } 96 | 97 | if ([values[prev] intValue] == key) 98 | { 99 | return prev; 100 | } 101 | 102 | return -1; 103 | } 104 | 105 | @end 106 | -------------------------------------------------------------------------------- /Chapter13/Objective-C/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // EverydayDataStructures 4 | // 5 | // Created by William Smith on 8/4/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "EDSIntegerTypes.h" 11 | #import "EDSFloatingTypes.h" 12 | #import "EDSBooleanType.h" 13 | #import "EDSStringType.h" 14 | #import "EDSLoggedInUserArray.h" 15 | #import "EDSUser.h" 16 | #import "EDSCollectionTests.h" 17 | 18 | #import "EDSArraySortingAlgorithms.h" 19 | 20 | int main(int argc, const char * argv[]) { 21 | @autoreleasepool { 22 | NSMutableArray *arr = [NSMutableArray arrayWithObjects:[NSNumber numberWithInteger:12], [NSNumber numberWithInteger:11], [NSNumber numberWithInteger:13], [NSNumber numberWithInteger:5], [NSNumber numberWithInteger:6], [NSNumber numberWithInteger:9], [NSNumber numberWithInteger:18], [NSNumber numberWithInteger:110], [NSNumber numberWithInteger:3], [NSNumber numberWithInteger:14], [NSNumber numberWithInteger:27], [NSNumber numberWithInteger:27], [NSNumber numberWithInteger:0], nil]; 23 | 24 | EDSArraySortingAlgorithms *algo = [[EDSArraySortingAlgorithms alloc] init]; 25 | 26 | // [algo selectionSortArray:arr]; 27 | // [algo insertionSortArray:arr]; 28 | // [algo bubbleSortArray:arr]; 29 | // [algo quickSortArray:arr forLowIndex:0 andHighIndex:arr.count - 1]; 30 | // [algo mergeSortArray:arr withLeftIndex:0 andRightIndex:arr.count - 1]; 31 | // [algo bucketSortArray:arr withMaxValue:110]; 32 | // [algo countingSortArray:arr]; 33 | [algo radixSortArray:arr]; 34 | 35 | for (NSNumber *num in arr) { 36 | NSLog(@"%li", (long)[num integerValue]); 37 | } 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Chapter13/Swift/ArraySearchAlgorithms.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ArraySearchAlgorithms.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 10/31/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | class ArraySearchAlgorithms 12 | { 13 | //Sequential / Linear 14 | open func linearSearhIndex( values: [Int], key: Int) -> Int 15 | { 16 | for i in 0.. Customer? 28 | { 29 | for i in 0.. Int 42 | { 43 | if (right >= left) 44 | { 45 | let mid: Int = left + (right - left) / 2 46 | 47 | if (values[mid] == key) 48 | { 49 | return mid 50 | } 51 | else if (values[mid] > key) 52 | { 53 | return binarySearch(values: values, left: left, right: mid - 1, key: key) 54 | } 55 | 56 | return binarySearch(values: values, left: mid + 1, right: right, key: key) 57 | } 58 | 59 | return -1 60 | } 61 | 62 | 63 | //Jump Search 64 | open func jumpSearch( values: [Int], key: Int) -> Int 65 | { 66 | let n: Int = values.count 67 | var step: Int = Int(sqrt(Double(n))) 68 | 69 | var prev: Int = 0 70 | 71 | while values[min(step, n) - 1] < key 72 | { 73 | prev = step 74 | step = step + Int(floor(sqrt(Double(n)))) 75 | if (prev >= n) 76 | { 77 | return -1 78 | } 79 | } 80 | 81 | while (values[prev] < key) 82 | { 83 | prev = prev + 1 84 | if (prev == min(step, n)) 85 | { 86 | return -1 87 | } 88 | } 89 | 90 | if (values[prev] == key) 91 | { 92 | return prev 93 | } 94 | 95 | return -1 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Chapter13/Swift/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // EverydayDataStructures-Swift 4 | // 5 | // Created by William Smith on 8/4/16. 6 | // Copyright © 2016 Websmiths, LLC. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | print("Hello, World!") 12 | 13 | var arr: [Int] = [12, 11, 13, 5, 6, 9, 18, 110, 3, 14, 27, 12] 14 | 15 | let algo: ArraySortingAlgorithms = ArraySortingAlgorithms() 16 | 17 | //algo.selectionSort(values: &arr) 18 | //algo.insertionSort(values: &arr) 19 | //algo.bubbleSort(values: &arr) 20 | //algo.quickSort(values: &arr, low: 0, high: arr.count - 1) 21 | //algo.mergeSort(values: &arr, left: 0, right: arr.count - 1) 22 | //algo.bucketSort(values: &arr, maxVal: 110) 23 | //algo.countingSort(values: &arr) //Doesn't like 0 24 | algo.radixSort(values: &arr) 25 | for num in 0.. Bool 17 | { 18 | if (_users.contains(user)) 19 | { 20 | return false; 21 | } else { 22 | return true; 23 | } 24 | } 25 | ``` 26 | 27 | In order for you to take full advantage of this book, you will need a modern computer. The code examples in this book are broad enough that you can use a Mac, PC, or even a Linux machine. Ultimately, you will also need a functioning development environment, such as Visual Studio, XCode, Eclipse, or NetBeans, that can run on your chosen development machine. 28 | 29 | ## Related Products 30 | * [Python Data Structures and Algorithm](https://www.packtpub.com/application-development/python-data-structures-and-algorithm?utm_source=github&utm_medium=repository&utm_campaign=9781786467355) 31 | 32 | * [Learning JavaScript Data Structures and Algorithms [Video]](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-video?utm_source=github&utm_medium=repository&utm_campaign=9781782175698) 33 | 34 | * [Learning Functional Data Structures and Algorithms](https://www.packtpub.com/application-development/learning-functional-data-structures-and-algorithms?utm_source=github&utm_medium=repository&utm_campaign=9781785888731) 35 | 36 | ### Suggestions and Feedback 37 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSe5qwunkGf6PUvzPirPDtuy1Du5Rlzew23UBp2S-P3wB-GcwQ/viewform) if you have any feedback or suggestions. 38 | ### Download a free PDF 39 | 40 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
41 |

https://packt.link/free-ebook/9781787121041

--------------------------------------------------------------------------------