Monday, March 27, 2017

Java Code: Calculate Sum of Digits till it becomes a Single Digit Number

The code should print something like this:

Now Number = 388
Initial Number:388
Sum = 19
Now Number = 19
Sum = 10
Now Number = 10

Sum = 1

Now let's Have a look at the code:


public class SumOfDigits {

    public static void main(String[] args) {

        int num = 388;
        int numOfDigits[] = calculateNumberOfDigits(num) ;
        System.out.println("Initial Number:" + num);
        while (numOfDigits.length>1){
            int sum = 0;
            for (int i = 0; i < numOfDigits.length; i ++){
                sum = sum + numOfDigits[i];
             }
            System.out.println("Sum = " + sum);
            if(sum < 10){
                break;
             }
             numOfDigits = calculateNumberOfDigits(sum);
         }
}

    public static int[] calculateNumberOfDigits(int num){
        System.out.println("Now Number = " + num);
        int numOfDigits = 0;
        int digits[] = new int[100];
        while(num>0){
            digits[numOfDigits] = num%10;
            num = num/10;
            numOfDigits = numOfDigits +1;
         }
        return digits;
     }

}

AngularJS: Share data across multiple Controller instances with Controller As Syntax

In this article we are going to discuss how to share data across multiple controller instances.

We are going to use service to share the data. Service in Angular follows Singleton pattern.


Once it is initialized, it will have only one object.

Now let's have a look at the code:

First let's look at the Service:

var sharedDataService = app.service('ShareDataService',ShareData);

function ShareData(){
  var shareDataService = this;
    
  shareDataService.searchQuery = "";
  
  shareDataService.getSearchQuery = function(){
 return shareDataService.searchQuery;
  }
  
  shareDataService.setSearchQuery = function(searchQuery){
 shareDataService.searchQuery = searchQuery;
  }
}

As we can see the service has one setter and one getter. 

Now let's define the module and the controller.

We have only one controller, and we inject the service in that controller.

var app = angular.module('app', []);

var appCtrl = app.controller('AppCtrl', AppCtrl);

appCtrl.$inject = ['ShareDataService'];

function AppCtrl(ShareDataService){
  var appCtrl = this;
  appCtrl.variable = "search";
 
   appCtrl.setSearchQuery = function () {    
       ShareDataService.setSearchQuery(appCtrl.variable);
    }
     
 appCtrl.getSearchQuery = function () {    
        return ShareDataService.getSearchQuery();
    } 
 
}

When we get the data, we first set the data in the service instance and then try to reprieve the data.

After all this is done let's look at the html code:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app = "app">
  <div ng-controller = "AppCtrl as ctrl1">
     {{ctrl1.getSearchQuery()}}
  </div>
  <div ng-controller = "AppCtrl as ctrl2">
    <input type="search" ng-model = "ctrl2.variable" ng-change="ctrl2.setSearchQuery()"/>
     {{ctrl2.variable}}
  </div>
</div>

Hope this is clear to you, if not just post a comment.

Friday, March 24, 2017

Generate All Permutations of a String

Suppose we are given a String and asked to find all the permutations of that String.

So for abcd it will be like:

bdAc
bdcA
cAbd
cAdb
cbAd
cbdA
cdAb
cdbA
dAbc
dAcb
dbAc
dbcA
dcAb

dcbA

The Java code should be the following:

public class StringPermutation {
    
    public static void main(String args[]){
        String perm = "Abcd";
        System.out.println(permutation("",perm));
    }
    public static String permutation(String prefix, String perm){
        if(perm.length() == 0){
            System.out.println(prefix);
 } else{
               for (int i = 0; i < perm.length(); i++){
                   permutation(prefix + perm.charAt(i), perm.substring(0,i
                      + perm.substring(i+1));
               }
}
        return prefix;
    }

}

Thursday, March 23, 2017

Fibonacci Series (Looping and Recursion)

This is a part of Interview Preparation Series I am preparing.

Today in this article we are going to discuss about Fibonacci series.

It's better if you have some idea about Recursion.

The code below has both the for loop way and the recursive way.


public class Fibonnaci {
// Output = 0 1 1 2 3 5 8 13
public static void main(String args[]){
int num = 20;
int fibSeries[] = fib(num);
System.out.println("Fibonacci by For loop:");
for (int i = 0; i < fibSeries.length; i ++){
System.out.print(fibSeries[i] + " ");
}
System.out.println("");
int fibSeriesRec[] = fibByRec(num);
System.out.println("Fibonacci by Recursion:");
for (int i = 0; i < fibSeriesRec.length; i ++){
System.out.print(fibSeriesRec[i] + " ");
}
}
public static int[] fibByRec(int num){
int fib[] = new int[num];
for (int i = 0 ; i < num; i ++){
fib[i] = fibRec(i);
}
return fib;
}
public static int[] fib(int num){
int fib[] = new int[num];
for(int i = 0; i < num; i ++){
if ( i == 0){
fib[i] = i;
continue;
}
if ( i == 1 || i == 2){
fib[i] = 1;
continue;
}
fib[i] = fib[i-1] + fib [i - 2]; 
}
return fib;
}
public static int fibRec(int num){
if(num == 0){
return 0;
}
else if (num == 1 || num == 2){
return 1;
}else {
return fibRec(num -1 ) + fibRec(num - 2);
}
}

}

The output:

Fibonacci by For loop:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 

Fibonacci by Recursion:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 

Decimal To Binary Conversion

Lte's have a look at the algorithm.

Let's take a number, say 59. Now let's convert it to Binary:

Number = 59

Divide:59/2
Quotient: 59
Remainder :1
Divide:29/2
Quotient: 29
Remainder :1
Divide:14/2
Quotient: 14
Remainder :0
Divide:7/2
Quotient: 7
Remainder :1
Divide:3/2
Quotient: 3
Remainder :1
Divide:1/2
Quotient: 1
Remainder :1
Binary Represenation of 59 = 111011


Now let's have a look at the code:

public class DecimalToBinary {

    public static void main(String[] args) {

        int num = 59;
        int digit = num;
        String binaryNum = "";
        while(true){
            System.out.println("Divide:" + digit + "/2");
            System.out.println("Quotient: " + digit);
            int remainder = digit%2;
            System.out.println("Remainder :" + remainder);
            binaryNum = String.valueOf(remainder) + binaryNum;
            digit = digit/2;
            if(digit<1){
               break;
            }
         }
         System.out.println("Binary Represenation of " + num + " = " + binaryNum);
       }
}

Tuesday, March 21, 2017

Service vs Factory vs Provider (AngularJS)

Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)
SERVICE:
Syntax:
app.js
 var app = angular.module('ServiceExample',[]);
 var serviceExampleController =
    app.controller('ServiceExampleController', ServiceExampleController);
 var serviceExample = app.service('NameOfTheService', NameOfTheService);

 ServiceExampleController.$inject = ['NameOfTheService']

function ServiceExampleController(NameOfTheService){
     serviceExampleController = this;
     serviceExampleController.data = NameOfTheService.getSomeData();
 }

function NameOfTheService(){
     nameOfTheService = this;
     nameOfTheService.data = "Some Data";
     nameOfTheService.getSomeData = function(){
           return nameOfTheService.data;
     }     
}
index.html
<div ng-controller = "ServiceExampleController as serviceExample">
   {{serviceExample.data}}
</div>
Features of Service:
  1. Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module.
  2. Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers.
FACTORY
First let's have a look at the syntax:
app.js:
var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);

//first implementation where it returns a function
function NameOfTheFactoryOne(){
   var factory = function(){
      return new SomeService();
    }
   return factory;
}

//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
   var factory = {
      getSomeService : function(){
          return new SomeService();
       }
    };
   return factory;
}
Now using the above two in the controller:
 var factoryOne = NameOfTheFactoryOne() //since it returns a function
 factoryOne.someMethod();

 var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
 factoryTwo.someMethod();
Features of Factory:
  1. Follows the factory design pattern. The factory is a central place that produces new objects or functions.
  2. Not only produces singleton, but customizable services.
  3. The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.
PROVIDER
Let's again have a look at the Syntax first:
angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional

Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
  ServiceProvider.defaults.maxItems = 10; //some default value
}


ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
  //some methods
}

function ServiceProvider() {
  var provider = this;

  provider.defaults = {
    maxItems: 10
  };

  provider.$get = function () {
    var someList = new someListService(provider.defaults.maxItems);

    return someList;
  };
}

}
Features of Provider:
  1. Provider is the most flexible method of creating services in Angular.
  2. Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application.
  3. The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods.
  4. The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factorymethod. In that function, we create our own service. This $get property, that's a function, is what makes the provider a providerAngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.