Tuesday, 2 August 2016

Calculate sum of all numbers present in a string

Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.

Input:  1abc23
Output: 24

Input:  sudhakar4sudhakar
Output: 4

Input:  1abc2x30yz67
Output: 100

Input:  123abc
Output: 123
 
 

The only tricky part in this question is multiple consecutive digits and considering as one number.
The idea is very simple. We scan each character of the input string and if a number is formed by consecutive characters of the string, we increment the result by that amount.
Below is its  implementation –
#include <iostream>
using namespace std;
/
int findSum(string str)
{
    // A temporary string
    string temp = "";
    // holds sum of all numbers present in the string
    int sum = 0;
    
    for (char ch: str)
    {
        // if current character is a digit
        if (isdigit(ch))
            temp += ch;
        // if current character is an alphabet
        else
        {
            // increment sum by number found earlier
            // (if any)
            sum += atoi(temp.c_str());
            // reset temporary string to empty
            temp = "";
        }
    }
    // atoi(temp.c_str()) takes care of trailing
    // numbers
    return sum + atoi(temp.c_str());
}
// Driver code
int main()
{
    // input alphanumeric string
    string str = "12abc20yz68";
    cout << findSum(str);
    return 0;
}
Output:

100
 
 
Time complexity of above solution is O(n) where n is length of the string.

Find next greater number with same set of digits

Given a number n, find the smallest number that has same set of digits as n and is greater than n. If x is the greatest possible number with its set of digits, then print “not possible”.
Examples:

For simplicity of implementation, we have considered input number as a string.

Input:  n = "218765"
Output: "251678"

Input:  n = "1234"
Output: "1243"

Input: n = "4321"
Output: "Not Possible"

Input: n = "534976"
Output: "536479"

Following are few observations about the next greater number.
1) If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321.
2) If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234.
3) For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)
You can now try developing an algorithm yourself.
Following is the algorithm for finding the next greater number.
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.
II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.
III) Swap the above found two digits, we get 536974 in above example.
IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.


Following is implementation of above approach.
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void swap(char *a, char *b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}
void findNext(char number[], int n)
{
    int i, j;
    
    for (i = n-1; i > 0; i--)
        if (number[i] > number[i-1])
           break;
    
    if (i==0)
    {
        cout << "Next number is not possible";
        return;
    }
    
    int x = number[i-1], smallest = i;
    for (j = i+1; j < n; j++)
        if (number[j] > x && number[j] < number[smallest])
            smallest = j;
    
    swap(&number[smallest], &number[i-1]);
    
    sort(number + i, number + n);
    cout << "Next number with same set of digits is " << number;
    return;
}
// Driver program to test above function
int main()
{
    char digits[] = "534976";
    int n = strlen(digits);
    findNext(digits, n);
    return 0;
}
Output:
Next number with same set of digits is 536479
The above implementation can be optimized in following ways.
1) We can use binary search in step II instead of linear search.
2) In step IV, instead of doing simple sort, we can apply some clever technique to do it in linear time. Hint: We know that all digits are linearly sorted in reverse order except one digit which was swapped.
With above optimizations, we can say that the time complexity of this method is O(n).


Evaluation of Expression Tree

Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree.
Examples:
Input :
Root node of the below tree
pic2

Output :
100

Input :
Root node of the below tree
pic1

Output :
110
We strongly recommend you to minimize your browser and try this yourself first.
As all the operators in the tree are binary hence each node will have either 0 or 2 children. As it can be inferred from the examples above , the integer values would appear at the leaf nodes , while the interior nodes represent the operators.
To evaluate the syntax tree , a recursive approach can be followed .
Algorithm :
Let t be the syntax tree
If  t is not null then
      If t.info is operand then  
         Return  t.info
      Else
         A = solve(t.left)
         B = solve(t.right)
         return A operator B
         where operator is the info contained in t

The time complexity would be O(n), as each node is visited once. Below is a C++ program for the same:
// C++ program to evaluate an expression tree
#include <bits/stdc++.h>
using namespace std;
 
// Class to represent the nodes of syntax tree
class node
{
public:
    string info;
    node *left = NULL, *right = NULL;
    node(string x)
    {
        info = x;
    }
};
 
// Utility function to return the integer value
// of a given string
int toInt(string s)
{
    int num = 0;
    for (int i=0; i<s.length();  i++)
        num = num*10 + (int(s[i])-48);
    return num;
}
 
// This function receives a node of the syntax tree
// and recursively evaluates it
int eval(node* root)
{
    // empty tree
    if (!root)
        return 0;
 
    // leaf node i.e, an integer
    if (!root->left && !root->right)
        return toInt(root->info);
 
    // Evaluate left subtree
    int l_val = eval(root->left);
 
    // Evaluate right subtree
    int r_val = eval(root->right);
 
    // Check which operator to apply
    if (root->info=="+")
        return l_val+r_val;
 
    if (root->info=="-")
        return l_val-r_val;
 
    if (root->info=="*")
        return l_val*r_val;
 
    return l_val/r_val;
}
 
//driver function to check the above program
int main()
{
    // create a syntax tree
    node *root = new node("+");
    root->left = new node("*");
    root->left->left = new node("5");
    root->left->right = new node("4");
    root->right = new node("-");
    root->right->left = new node("100");
    root->right->right = new node("20");
    cout << eval(root) << endl;
 
    delete(root);
 
    root = new node("+");
    root->left = new node("*");
    root->left->left = new node("5");
    root->left->right = new node("4");
    root->right = new node("-");
    root->right->left = new node("100");
    root->right->right = new node("/");
    root->right->right->left = new node("20");
    root->right->right->right = new node("2");
 
    cout << eval(root);
    return 0;
}
Output:
100
110

Monday, 1 August 2016

Default Methods In Java

Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.
// A simple program to Test Interface default
// methods in java
interface TestInterface
{
    // abstract method
    public void square(int a);
 
    // default method
    default void show()
    {
      System.out.println("Default Method Executed");
    }
}
 
class TestClass implements TestInterface
{
    // implementation of square abstract method
    public void square(int a)
    {
        System.out.println(a*a);
    }
 
    public static void main(String args[])
    {
        TestClass d = new TestClass();
        d.square(4);
 
        // default method executed
        d.show();
    }
}
Output:
 16
 Default Method Executed
The default methods were introduced to provide backward comparability so that existing intefaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods.
Static Methods:
The interfaces can have static methods as well which is similar to static method of classes.
// A simple Java program to TestClassnstrate static
// methods in java
interface TestInterface
{
    // abstract method
    public void square (int a);
 
    // static method
    static void show()
    {
        System.out.println("Static Method Executed");
    }
}
 
class TestClass implements TestInterface
{
    // Implementation of square abstract method
    public void square (int a)
    {
        System.out.println(a*a);
    }
 
    public static void main(String args[])
    {
        TestClass d = new TestClass();
        d.square(4);
 
        // Static method executed
        TestInterface.show();
    }
}
Output:
 16
 Static Method Executed
Default Methods and Multiple Inheritance
In case both the implemented interfaces contain deafult methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.
// A simple Java program to demonstrate multiple
// inheritance through default methods.
interface TestInterface1
{
    // default method
    default void show()
    {
        System.out.println("Default TestInterface1");
    }
}
 
interface TestInterface2
{
    // Default method
    default void show()
    {
        System.out.println("Default TestInterface2");
    }
}
 
// Implementation class code
class TestClass implements TestInterface1, TestInterface2
{
    // Overriding default show method
    public void show()
    {
        // use super keyword to call the show
        // method of TestInterface1 interface
        TestInterface1.super.show();
 
        // use super keyword to call the show
        // method of TestInterface2 interface
        TestInterface2.super.show();
    }
 
    public static void main(String args[])
    {
        TestClass d = new TestClass();
        d.show();
    }
}
Output:
Default TestInterface1
Default TestInterface2
Important Points:
  1. Interfaces can have default methods with implementation from java 8 onwards.
  2. Interfaces can have static methods as well similar to static method of classes.
  3. Default methods were introduced to provide backward comparability for old interfaces so that they can have new methods without effecting existing code.