Category Archives: C/C++/Objective-C

Hash Map (chaining)

demo

ref –
http://www.algolist.net/Data_structures/Hash_table/Chaining
http://stackoverflow.com/questions/9214353/hash-table-runtime-complexity-insert-search-and-delete

Hash Map with Chaining

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.

When the number of entries in the hash table exceeds the product of the load factor and the current capacity,
the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has
approximately twice the number of buckets.

The Node

.h file

.cpp file

The Hash Map

HashTable.hpp

The way we go about creating the Hash Table is by using an array of pointers. Each pointer at array[i] will point to a node. That node can link to another node. This is so that we can have an array of linked list. Which by definition, is what constitutes a chained hash map.

Thus, we use double pointers to point to this array of pointers: LinkedHashEntry ** table.

*table (or table[0]) dereferences the 1st array element.
*(table+1) (or table[1]) dereferences the 2nd array element.
..and so on

In order to allocate memory, we allocate this array of pointers on the heap.

Think of it like this:

We want to allocate on the heap (new)
an array of certain size ([MAX])
of LinkedHashEntry pointers (LinkedHashEntry *):

LinkedHashEntry ** table = new LinkedHashEntry * [MAX]

By definition, we always have a pointer pointing to the address of the first element of the array.

In every array, we always assign an array anchor (a pointer) to the 1st element of the array.
For example, an array of integers, int * i = new int [8];

int * i points to the first integer element’s address.
*i will dereference and get the int value.

In our case, since our first element is a pointer, we need a pointer to a pointer to act as the array anchor, and that is
why we use LinkedHashEntry ** table.

Now, we have an array of LinkedHashEntry pointers, and we are set to work.

Insertion

While certain operations for a given algorithm may have a significant cost in resources, other operations may not be as costly.

Amortized analysis considers both the costly and less costly operations together over the whole series of operations of the algorithm. This may include accounting for different types of input, length of the input, and other factors that affect its performance

insertion O(1) average and amortized case complexity, however it suffers from O(n) worst case time complexity.

BUT WHY?
Hash tables suffer from O(n) worst time complexity due to two reasons:

If too many elements were hashed into the same key. Thus, it degrades into a linked list
for that particular slot. Searching through this list may take O(n) time. see 2), where it keeps appending elements at the same slot.

Once a hash table has passed its load balance, it has to rehash [create a new bigger table, and re-insert each element to the table].

The reason why it is O(1) average and amortized case because:

  • It is very rare that many items will be hashed to the same key
  • if you chose a good hash function and you don’t have too big load balance.
  • The rehash operation, which is O(n), can at most happen after n/2 ops
  • which are all assumed O(1): Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)

Deletion

Deletion has the same concept as Insertion. Amortized case O(1), worst time O(n).

deleteNode is just a simple function that sets a LinkedHashEntry pointer to NULL and wipes out everything.

recurseAndRemove uses recursion to run through a list of LinkedHashEntry nodes, and remove the node with the specified key.

The list of nodes is given by LinkedHashEntry ** temp. Pointer of a pointer means that the double pointer points to the the address of a pointer. That pointer points to the address of the node.

hashentry_dblptr

Hence, if we want to reassign the pointer at this->table[i] to another node, it means:

this->table[i] is a pointer, thus we have to use a double pointer (HashEntry ** temp) to point to this->table[i]. Deference it like this (*temp) to control the pointer this->table[i] itself….and assign it to another node as shown in the image.

If we simply have a pointer like HashEntry * singlePtr = this->table[i], it won’t work because singlePtr will be pointing to whatever this->table[i] is pointing to. singlePtr is pushed onto the local stack, and has nothing to do with the pointer that is this->table[i].

singlePtr simply points to whatever this->table[i] points to. singlePtr is pushed onto the local stack

Once you understand this, the rest is just simple recursion and node traversal.

There are 2 cases:

  • You need to remove the first node. This means in order to get control of the first pointer, you need to get the address of the initial pointer, dereference it (at this point, you have full control of the pointer) and point it
  • You need to remove 2nd..and after node. This is simple because dereferencing the temp pointer gives you full control of the next pointer.

Doubly Linked List

xCode demo

Tests

.hpp

.cpp file

Passing Blocks as parameter to other Blocks

What we’re trying to accomplish

Say you have class BackgroundTask that retains a block elsewhere and will run it in your app like so:

The block of code that property task points to is something like this:

So somewhere within the task, when we reach a certain point, we want to communicate to Background task that we want it to do say, do some clean up. How do we communicate back to BackgroundTask?

Solution – Pass in a reply block

1) declare a block with a block parameter

This means that we declare a block called OnBackgroundTask, which returns void. However, it does take 1 parameter of type CleanUpBackgroundTask.

where CleanUpBackgroundTask returns void and takes no parameters

We will be using CleanUpBackgroundTask to communicate back to BackgroundTask.

2) declare the reply block with code definition, then pass it into the original block during the call

So when using the code, you provide a block of code for the task like so:

self.task now points to the block of code you just provided. cleanup block currently is not defined. We can define it right before you call self.task and pass it in.

At this point, the task code is called, your code task will run, and the cleanUp() will naturally be called within code ‘task’.

block-passing

How to deal with erroneous server db deletion

xCode 7.3 demo

UPDATE 8/17/16

If you want to remove local AND server data, all you have to do is call the delete method from your MSSyncTable.
It sends a request to your local data source to remove the given item, then queues a request to send the delete
to the mobile service.

It first removes the data locally.
Then, when the queued request goes through into the mobile service, then it will update remotely,
and you can log into your Azure account, look at the Easy Tables, and see that the item has been removed.

Let’s say you have added 4 entries:

leftover_1

The database reflects this:

leftover_2

Then, let’s say there is a direct deletion in the DB. The item we deleted it is has id A24D9651-A252-4A70-81A8-61520BB5C0D1

leftover_3

Now, even though this is not the way Microsoft wants us to do deletion, we do need a way to sync our local DB with the server DB just in case this happens.

Open the project. Let’s implement a log method to display the data in our local db.

QSAppDelegate.h

The logging is to verify correctness of local db. It is also used to get the id of users you want to delete.

For example, on the server side, if someone deletes Ivan, and in case you forgot to safe the ID, you can always use the log method to display the local results:

2 — text = Ivan, id = 46206A2F-26A7-4667-8A8E-391CA51EE731

QSAppDelegate.m

Delete – server and local

Then, let’s write the delete method for the service, so that we can remove the server data, and the local data.

Notice that we use MSTable’s deleteWithId to remove the item from the server.

We use MSSyncTable’s delete:item to remove item locally.

QSTodoService.h

QSTodoService.m

Now, given an ID, let’s check to see if the server has that ID. Insert the ID of the item you just deleted (A24D9651-A252-4A70-81A8-61520BB5C0D1) into rowId.

For matching local data wit direct delete in the server DB, we simply use local delete.

For simplicity purposes, we’ll just do the logging, and checking in refresh method of QSTodoListViewController:

Run the program…first you’ll see the logging to prove that your local database is out of sync with the server database:

2016-08-16 16:19:42.297 EpamEvents[4441:456591] -[QSAppDelegate logAllTodoItem] – logAllTodoItem method called
2016-08-16 16:19:42.297 EpamEvents[4441:456591] ———— RESULTS FROM DATABASE ————
2016-08-16 16:19:42.298 EpamEvents[4441:456591] 4
2016-08-16 16:19:42.298 EpamEvents[4441:456591] 0 — text = Dean, id = 1D9AB54C-793A-4240-A8FB-3E968BB16D09
2016-08-16 16:19:42.298 EpamEvents[4441:456591] 1 — text = Ricky, id = A24D9651-A252-4A70-81A8-61520BB5C0D1
2016-08-16 16:19:42.298 EpamEvents[4441:456591] 2 — text = Ralph, id = 49E6A521-CB9D-4D37-9CEB-F81403707202
2016-08-16 16:19:42.299 EpamEvents[4441:456591] 3 — text = Ivan, id = 46206A2F-26A7-4667-8A8E-391CA51EE731

Then, when you run through the method, you will see the checkServerDeletionCompletion method call readWithId. First it checks for item (A24D9651-A252-4A70-81A8-61520BB5C0D1). Remember, someone has mistakenly deleted this item from the DB directly, hence you’ll get an error warning like so:

2016-08-16 16:20:06.084 EpamEvents[4441:456591] Error Domain=com.Microsoft.MicrosoftAzureMobile.ErrorDomain Code=-1302 “The item does not exist” UserInfo={NSLocalizedDescription=The item does not exist, com.Microsoft.MicrosoftAzureMobile.ErrorRequestKey= { URL: https://epamevents.azurewebsites.net/tables/TodoItem/A24D9651-A252-4A70-81A8-61520BB5C0D1 }, com.Microsoft.MicrosoftAzureMobile.ErrorResponseKey= { URL: https://epamevents.azurewebsites.net/tables/TodoItem/A24D9651-A252-4A70-81A8-61520BB5C0D1 } { status code: 404, headers {
“Cache-Control” = “no-cache”;
“Content-Length” = 35;
“Content-Type” = “application/json; charset=utf-8”;
Date = “Tue, 16 Aug 2016 08:19:58 GMT”;
Etag = “W/\”23-xvKyQMaUWUD9x7DI0LISBQ\””;
Expires = 0;
Pragma = “no-cache”;
Server = “Microsoft-IIS/8.0”;
“Set-Cookie” = “ARRAffinity=871fe01e072348697c5ee601ae1b8377c6473f1f3b3bb965170b664f5c32221d;Path=/;Domain=epamevents.azurewebsites.net”;
“X-Powered-By” = “Express, ASP.NET”;
} }}

Then once the error is noticed, we delete it from our local via the delete method. As you can see, locally, Ricky has been deleted.

The result is:

2016-08-16 16:20:06.091 EpamEvents[4441:457812] DELETED LOCALLY!
2016-08-16 16:20:09.886 EpamEvents[4441:456591] -[QSAppDelegate logAllTodoItem] – logAllTodoItem method called
2016-08-16 16:20:09.887 EpamEvents[4441:456591] ———— RESULTS FROM DATABASE ————
2016-08-16 16:20:09.887 EpamEvents[4441:456591] 3
2016-08-16 16:20:09.887 EpamEvents[4441:456591] 0 — text = Dean, id = 1D9AB54C-793A-4240-A8FB-3E968BB16D09
2016-08-16 16:20:09.888 EpamEvents[4441:456591] 1 — text = Ralph, id = 49E6A521-CB9D-4D37-9CEB-F81403707202
2016-08-16 16:20:09.888 EpamEvents[4441:456591] 2 — text = Ivan, id = 46206A2F-26A7-4667-8A8E-391CA51EE731

_cmd

http://stackoverflow.com/questions/4418233/cmd-value-inside-c-functions

The first two parameters passed to all Objective-C methods are self and _cmd, then whatever other arguments the actual method takes.

Loose Coupling through Dependency Injection

https://yalantis.com/blog/dependency-injection-di-service-locator/
http://stackoverflow.com/questions/3058/what-is-inversion-of-control

In case the link does not work, the article can be downloaded and opened from your local machine here

Dependency Injection

Interface Injection

The Problem

follow along with the code in Dependency Injection

Say you have a MovieLister object that has a method moviesDirectedByDirector. It uses a class called TextFileMovieFinder in order to call methods on it and get return values for the results.

This is the simplest solution, but yet, it creates tight-coupling because the method full depends on the exact implementation of TestFileMovieFinder.

Implementing a protocol and using delegate for loose coupling

In the MovieLister, our job is to list. We just need to connect it to a movie finder that gives us the results.

We do this by having a delegate that points to any object that conforms to MovieFinder.
That way, we don’t care what that object does, just give us the result via the protocol MovieFinder’s

..and you use it like so:

Now, let’s update our TextFileMovieFinder object so that it conforms to the MovieFinder protocol.

TextFileMovieFinder.h

TextFileMovieFinder.m

But how do we connect them?

1) Constructor Injection

constructor_injection

Constructor injection is perfect for “obligatory” dependencies, without which the class can’t implement its task. This way we locate all the dependencies in one place – in the constructor. When the class expands and starts using additional services, they will appear in the constructor as parameters which cannot be left unnoticed. So when another parameter is added to the constructor and the number of all the parameters becomes higher than 4, you need to think about the architecture of your class.

2) Setter Injection

setter_injection

Setter injection (property injection) fits “optional” dependencies, those which have a reasonable implementation known to the class by default. At the same time there has to be a possibility to change the dependency while the class is working and without any negative consequences.

Delegates

http://stackoverflow.com/questions/7052926/what-is-the-purpose-of-an-ios-delegate

The advantage of the delegate design pattern is loose coupling. It enables class A (the delegate) to depend on class B (the delegating class) without class B having to have any knowledge of class A. This ensures that the dependency relationship is one-way only, rather than being circular.

It also forms the foundation (lower case “f”) of Apple’s frameworks because it allows them to invoke your code as appropriate when functionality specific to your application is required. For example, responding to a button tap or telling a table view how many sections there should be.

Why use hex to represent memory address locations in Programming

https://learn.sparkfun.com/tutorials/hexadecimal
http://stackoverflow.com/questions/14113051/how-to-calculate-size-of-memory-by-given-a-range-of-address

The hexadecimal system is commonly used by programmers to describe locations in memory because:

1) it can represent every byte (i.e., eight bits) as two consecutive hexadecimal digits instead of the eight digits that would be required by binary (i.e., base 2) numbers

BINARY
_ _ _ _ _ _ _ _ = 8 bits = 1 byte.

2 2 2 2 2 2 2 2 = 2^8 = 256 representations (memory addresses)

HEX
_ _ where each bit has 16 representations (0-9, a-f) so
16 16 = 16 ^ 2 = 256 representations (memory addresses)

2) and the three digits that would be required with decimal numbers.

example

_ _ _ _ _ _ _ _ ( 8 bits )

0 0 0 0 0 0 0 0 ( 1 )
0 0 0 0 0 0 1 1 ( 2^1 + 2^0 = 3 )
0 0 0 0 1 0 1 0 ( 2^3 + 2^1 = 8 + 2 = 10 )
1 1 1 1 1 1 1 1 ( 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255

where each number represent a memory location.

Hence, 8 bits we can represent from from 0 – 255, or 256 different memory locations.

However, the 8 bit representation is difficult visually.

The hex system can represent 256 memory addresses with just 2 hex digits.

0 0 ( 0 )
0 3 ( 3 )
0 10 ( 10 )
F A ( 15 * 16^1 + 10 * 16^0 = 240 + 10 = 250 )
F F ( 15 * 16^1 + 15 * 16^0 = 255 )

In addition, it is much easier for humans to read hexadecimal numbers than binary numbers, and it is not much more difficult for computer professionals to read hexadecimal numbers than decimal numbers.

Converting from Decimal to Hex

Say we want to convert 61453 to hex.

61352/16 = 3840 R13 (13 in hex is D)
3840 /16 = 240 R0 (0 in hex is 0)
240 /16 = 15 R0 (0 in hex is 0)
15 /16 = 0 R15 (15 in hex is F)

Hence the resulting conversion to hex is 0xF00D

Converting from Hex to Decimal

0xF00D

F * 16^3 + 0 * 16^2 + 0 * 16^1 + D * 16^0
15 * 4096 + 0 * 256 + 0 * 16 + 13 * 1 = 61440 + 0 + 0 + 13 = 61453

Binary to Hex

We use hex in electrical and computer engineering because it’s incredibly easy to convert to and from binary – the 1’s and 0’s language of computers.

each digit of a hexadecimal number “maps” to four bits (a bit being an individual binary digit) of a binary value.

a hex decimal is: 0-15, which is 16 digits. 16 representations.

In binary, we need 4 bits to make 16 representations:

0000 = 0
1111 = 15

Hence that is how ONE hex bit “maps” to FOUR binary bits.

Going further a byte – eight binary digits – can be represented by two hexadecimal digits.
This makes hex a really great, concise way to represent a byte or group of bytes.

From binary to hex

binary: 0b101111010100001

sort them into group of 4s:

0101 1110 1010 0001
5 E A 1

From hex to binary

Take a hex digit and turn it into four binary digits:

0 x B E E F

B is 11
11 in binary is 1 0 1 1

E is 14
14 in binary is 1 1 1 0

F is 15
15 in binary is 1 1 1 1

Hence 0 x BEEF in binary is

1011 1110 1110 1111

Easily representing values of bytes

Hex is often easier for us to work with because the values are shorter and more memorable than a long string of 1’s and 0’s.

Let’s say:

CTRL_REG2_G is the name of the register, with address 0010 0001

it’s much easier to remember 0x21 than 0b010001
For that reason, we’re much more likely to use hex values in our code than their binary equivalents.

Working with programming languages in IDE

Often in IDEs, when you are debugging, you’ll see hex addresses assigned to your variables.

For example, say you create an array:

If you print out the addresses of each integer, you

you’ll see the list of addresses for each integer

Given that we created an array of 8 integer elements,
each int can represent up to 4 bytes (or 4 * 8 bits = 2^32 bits) of data.

This means each integer can have 2^32 representations.

For example,
-2,147,483,648 to 2,147,483,647 as a signed int (signed means negative and positive)
or 0 to 4294967296 as an unsigned int.

We see that the 1st int’s starting address is at 0x1004000a0.
the 2nd int’s starting address is at 0x1004000a4.

So how does an int sit at 0x1004000a0 to 0x1004000a4-1, and to mean 4 bytes?

Most CPU has the 1 byte address architecture. This means that each address contains 1 byte or 8 bits.
Hence, at 0x1004000a0, there is a register that can store 8 bits (or 1 byte) of information.

In other words, at 0x1004000a0, we can contain anywhere from 00000000 to 11111111.

at 0x1004000a1, we can contain another byte of data.

at 0x1004000a2, we can contain another…

Hence from 0x1004000a0 to 0x1004000a3, we have a total of 4, 1 byte registers, that we can store data.

It can store any representations from:
00000000 00000000 00000000 00000000


11111111 11111111 11111111 11111111

Therefore if we have 4 registers, that means we can store 2^(4 * 8bits) different representations of data.

Since an int can represent 4294967296 different datas, it needs 4 bytes or 32 bits to do it.
That is why an int’s address starts at 0x1004000a0, and ends at 0x1004000a4 – 1.

Requesting what you need, and getting what you want

How to achieve loose coupling

original article on why loose coupling is needed
http://martinfowler.com/articles/injection.html

how to achieve loose coupling in iOS
http://code.tutsplus.com/articles/design-patterns-delegation–cms-23901

If you do not do this…this will happen

https://blogs.msdn.microsoft.com/scottdensmore/2004/05/25/why-singletons-are-evil/

How we achieve loose coupling in Events App using protocols

In detail: UIViewController to Module

Make sure you conform to RecentActivityViewInterface so that you can receive data from delegate methods.

Then create a delegate that conforms to RecentActivityInterface so you can call methods that you need.

ViewController.m
Implement the delegate method so we can receive the results:

ViewController.m
Hook everything up

Then use it like so:

Pass data from UITableViewCell to UIViewController

http://stackoverflow.com/questions/9005052/recipes-to-pass-data-from-uitableviewcell-to-uitableviewcontroller

Solution: Use custom delegate

UIViewController

MyViewController.h

MyViewController.m

Custom table cell and Protocol

MyTableViewCell.h

MyTableViewCell.m