Sunday, August 14, 2016

Coding problems to refresh your brain

Coding problems that I have come across recently:

1. Add two simple mathematical expressions which are of the form Axa + Bxb + ...

2. Print nth number of Fibonacci series using iterative loop.

3. Iterate and print every element of a n-child binary tree

4. Dollar Words:

acalephe
acclimatizable
acclimatizer
acclimatizers
accorage

Using a C# console application, give each letter in each word a numerical value equal to its position in the alphabet.  So "a" is 1 and "z" is 26.  Punctuation and whitespace is 0.  Find words where the sum of the value of the letters is 100 and print each of the “100” words on the console.

5. In the programming language of your choice, write a method that modifies a string using the
following rules:

- Each word in the input string is replaced with the following: the first letter of the word, the count of
distinct letters between the first and last letter, and the last letter of the word. For
example, “Automotive parts" would be replaced by "A6e p3s".
- A "word" is defined as a sequence of alphabetic characters, delimited by any non-alphabetic
characters.
- Any non-alphabetic character in the input string should appear in the output string in its original
relative location

6 a)An array contains 0s and 1s. Write a function to sort all the 0s to the left and the 1s to the right.
b) Check if array is sorted i.e. if all the 0s are to the left and 1s are to the right.

7. Convert date strings in the following formats  'M/d/yyyy' , 'MM/d/yyyy', 'M/dd/yyyy' to 'MM/dd/yyyy'.  This is a real life problem that I had to fix for the dates in my company's database.

Sunday, June 19, 2016

How reference types are passed to functions

I used to have this confusion about what exactly happens when reference types are passed by value to functions till recently. Let me illustrate what I have learnt since then with a few examples:

           static void Main(string[] args)
        {
            string s = "UNITED";
            ChangeString(s);
            Console.WriteLine(s);

            StringBuilder a = new StringBuilder("UNITED");
            ChangeSb(a);
            Console.WriteLine(a);
            Console.Read();
     
       }  
        private static void ChangeString(string s1)
        {
         
            s1 += "STATES";
        }

    private static void ChangeSb(StringBuilder a1)
        {
            a1.Append("STATES");
        }

Output:
UNITED
UNITEDSTATES

Explanation:
So reference types always contain the memory location of the data and not the actual data itself. In the above example s will contain the memory location where 'United' is stored . And then when ChangeString(s) the new variable s is assigned the same memory location that contains 'United'. However when 'States' is appended to it, since string are immutable, a new string is created which contains the memory location of the word 'States'. Therefore, when we output s we still get 'United' since the original variable is untouched. For this example, lets assume the entire word is stored at that memory location because it is not important.



In the case of the StringBuilder a, it again points to the memory location where 'United' is stored. When ChangeSb(a) is called, the new StringBuilder contains the memory location where 'United' is stored.

When "States" is appended to it, the memory location will now contain "United States". A new location is not used since StringBuilders are not immutable.

And another example:

         static void Main(string[] args)
        {
            string s = "UNITED";
            ChangeString(s);
            Console.WriteLine(s);

            StringBuilder a = new StringBuilder("UNITED");
            ChangeSb(a);
            Console.WriteLine(a);
            Console.Read();
      }
     
   
        private static void ChangeString(string s)
        {
             s = "STATES";
       
        }

  private static void ChangeSb(StringBuilder a)
        {
            a = new StringBuilder("STATES");
         
        }


Output:
UNITED
UNITED

Saturday, May 21, 2016

JSON using JavaScriptSerializer in C#

I had to work with JSON recently to integrate the Payeezy gateway to our website. First time I used the dynamic type in C#. Below is the code I used to create the JSON:



 dynamic payload = new
        {
            merchant_ref = "Payeezy Token test",
            transaction_type = "purchase",
            method = "token",
            amount = amt,
            currency_code = "USD",
            token = new
            {
                token_type = "FDToken",
                token_data = new
                {
                    type = cardType,
                    value = transarmorTokenValue,
                    cardholder_name = cardHolder,
                    exp_date = expMonth+expYear
                }
            }
        };
        jsonString = JSONHelper.ToJSON(payload);



In order to parse the response JSON:

StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());
responseString = responseStream.ReadToEnd();
 var responseValues = JSONHelper.ToDictionaryStringObject(responseString);
  int bankResponse = Convert.ToInt32(responseValues["bank_resp_code"]);



    
The JSONHelper class:

public static class JSONHelper
{
    public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);
    }


  public Dictionary<string, object> ToDictionaryStringObject(string s)
{
       var json = new JavaScriptSerializer();
       return json.Deserialize<Dictionary<string, object>>(s);
}

}

Thursday, May 19, 2016

2 applications instead of 1

These days whenever you build a complex website such as an insurance/benefits enrollment system you plan for 2 applications instead of 1.

The first application is obvious. It is the system in which your customers would use to enroll into their benefits.

The second application is an administration system for the benefits enrollment system. So that non technical employees can configure the system as per the business requirements and your input is not needed for every small change.

In the self enrollment system we have at our company, I have so far built the following admin features:

1. HTML text-boxes where the user can configure popups to be shown on different pages of the self enrollment system.

2. Make a user admin on the website with special privileges.

3. Delete all future deductions (selected plan amount) of users of a particular group. This feature is useful when the sales team has to give demos of our website.

4. Enable or disable a product on the self enrollment system.

5. Changing whether current deduction (last year's deduction amount) is visible on top of every product screen per group.

I'll keep adding features as our product evolves. 

Saturday, May 14, 2016

Is the field 'tobacco user' redundant?

I work in the insurance industry right now and we have a concept of rate tables which we display the rates that is applicable to a customer as per his demographics such as age and tobacco usage. 

For one particular product we have two rate tables depending on whether the customer is a tobacco user or not. The appropriate rates are shown to customer on the screen depending on his answer to the question about his tobacco usage.



My confusion is how to store the fact whether the customer is a tobacco user or not. I know we should not create redundant columns in a database table  Every time the customer makes a selection and enroll's in a policy his action is recorded in the transactions table. Would it be redundant to create a column in this transactions table that records whether the customer is a tobacco user? Because the rate that the customer selected is recorded and this can be matched to the corresponding rate table to identify whether the user is a tobacco user or not.

But then later, when we have to create reports about customer demographics. In order to identify the tobacco usage status of a customer we would need to execute two queries and if the 'tobacco user' column is present we would need only one.

What is your opinion?

Sunday, May 8, 2016

How to change the width of popup after initialization?


I set the width of the popup as auto when initialized in JQUERY script file which is shared with several pages on my website:


 $("#modal-dialog").dialog({
        autoOpen: false,
        modal: true,
        resizeable: false,
        position: { my: 'top', at: 'top+100' },
        height: 'auto',
        width: 'auto',
        buttons: {
            Close: function () {
                $(this).dialog("close");
            }
        },
        show: {
            effect: "drop",
            duration: 400,
            direction: "up"
        },
        hide: {
            effect: "drop",
            duration: 400,
            direction: "down"
        }
    });


And on a particular page I put the following code in the HTML. I am filling the contents in the server code

  <div id="modal-dialog" title="">
                                <div id="dialogContent" runat="server" clientidmode="Static">
                                    </div>
                                    </div>
    
                          
Now try as I may to resize the width it wouldn't work.

 var dialogW = $(window).width() * 0.7;
                        $("#modal-dialog").css("width", dialogW);
                     
                     
However all I needed to do was add this line and it worked:

  $("#dialogContent").css("width", dialogW);
                   
Which means that you need to re-size the content in order to re-size the popup. This way your popup can be of different widths on different pages.

Monday, April 25, 2016

Why create functions?

Going back to the basics today. I personally worked on several programs where the authors have just wrapped all the code in a single function and it has worked! An example, suppose you are working on an ASP.NET website - just stuff everything into the page life cycle Page Load function!

But I am a firm believer in creating functions to segregate your code since it has the following advantages:


  1. Problem solving: They allow us to conceive of our program as a bunch of sub-steps. (Each sub-step can be its own function. When any program seems too hard, just break the overall program into sub-steps!). [1]
  2. Code reuse: They allow us to reuse code instead of rewriting it. [1] This will also reduce the length of your code file. 
  3. Garbage collection: Functions allow us to keep our variable namespace clean (local variables only "live" as long as the function does). In other words, function_1 can use a variable called i, and function_2 can also use a variable called i and there is no confusion. Each variable i only exists when the computer is executing the given function. [1]
  4. Unit testing: Functions allow us to test small parts of our program in isolation from the rest. [1] This is fantastic for Unit Testing. So is dependency inversion. 
  5. Maintainability: It makes it easy to maintain the code since the length of your file is small. And further, if you make changes to the function the new code is automatically propagated to every where the function is called. On the other hand, if you have not created functions, you would have to change the code everywhere either by searching for it or waiting till your program crashes :).

Image source: Wikipedia


When should you create functions?

  1.  Duplicated code: When the same code repeats in several places. This was and still is a thumb rule. 
  2. Long methods: All other things being equal, a shorter method is easier to read, easier to understand, and easier to troubleshoot. Refactor long methods into smaller methods if you can. [2]
  3. Single responsibility principle: If a method has more than one responsibility it can lead to a violation of SRP. [3]
References: 
1. http://www.cs.utah.edu/~germain/PPS/Topics/functions.html
2. http://blog.codinghorror.com/code-smells/
3. http://programmers.stackexchange.com/questions/275646/is-the-single-responsibility-principle-applicable-to-functions