Thursday, 24 November 2016

Printing characters with their count in a String

Total number of Character in ASCII table is 256 (0 to 255). 0 to 31(total 32 character ) is called as ASCII control characters (character code 0-31). 32 to 127 character is called as ASCII printable characters (character code 32-127). 128 to 255 is called as The extended ASCII codes (character code 128-255)

There are multiple solution available with O(n) time and space complexity using Set,Map , O(n2) using Brute force iterating each character element of a String.

Solution 1 : 

But I am representing a solution with O(n) time complexity and In place O(1) space complexity as follow : 



/**

 * @author sachin
 *
 */
public class CountDuplicates {
public static void charsCount(String str){
int[] intArr = new int[256];
char[] charArrInputstr.toCharArray();
int charLength = charArrInput.length;
for (int i = 0; i < charLength; i++) {
intArr[charArrInput[i]]++;
}
int j =0;
for (int c : intArr) {
if(c > 0){
System.out.println( "char=" + (char)j + " and count=" + c );
}
j++;
}
}
public static void main(String[] args) {
String a = "My Name Is Sachin Srivastava and I am a Java Architect passionate "
+ "about writing,blogging & coding , author of tek9g.blogspot.com and vedology.blogspot.com";
charsCount(a);
}
}

Output :


char=  and count=21
char=& and count=1
char=, and count=2
char=. and count=4
char=9 and count=1
char=A and count=1
char=I and count=2
char=J and count=1
char=M and count=1
char=N and count=1
char=S and count=2
char=a and count=15
char=b and count=4
char=c and count=6
char=d and count=4
char=e and count=5
char=f and count=1
char=g and count=9
char=h and count=3
char=i and count=8
char=k and count=1
char=l and count=4
char=m and count=4
char=n and count=7
char=o and count=14
char=p and count=3
char=r and count=4
char=s and count=6
char=t and count=10
char=u and count=2
char=v and count=4
char=w and count=1
char=y and count=2


Solution 2 :

Using a HashMap : O(n) time and space complexity


       
Map<Character, Integer> map = new HashMap<>();
char[] charArrInputstr.toCharArray();
for (char c : charArrInput) {
if(!map.containsKey(c)){
map.put(c, 1);
} else {
map.put(c, map.get(c)+1);
}
}
for (Entry<Character, Integer> entry : map.entrySet()) {
System.out.println("char=" + entry.getKey() + " and count=" + entry.getValue());
}
Output:
char=A and count=1
char=I and count=2
char=J and count=1
char=M and count=1
char=N and count=1
char=S and count=2
char=  and count=21
char=a and count=15
char=b and count=4
char=c and count=6
char=d and count=4
char=e and count=5
char=& and count=1
char=f and count=1
char=g and count=9
char=h and count=3
char=i and count=8
char=k and count=1
char=, and count=2
char=l and count=4
char=m and count=4
char=n and count=7
char=. and count=4
char=o and count=14
char=p and count=3
char=r and count=4
char=s and count=6
char=t and count=10
char=u and count=2
char=v and count=4
char=w and count=1
char=y and count=2
char=9 and count=1


Solution 3 :   Using brute force in the O(n2)   , basically iterating each  n element and comparing and counting remaining  n-1 element  making it quadratic solution with respect to time.

Solution 3 is not recommended , Solution 1 is the best solution and if one not able to do like solution1 then Solution 2 would be simple to use.

Enjoy tek9g  blog and coding !!!!!!!!!

Sunday, 20 November 2016

Making PDF Password protected in Java


There are various libraries available through to which a pdf can protected with password encryption.

Full maven repository is available here

But as a developer , I am using here itextpdf library and bouncyCastle libraries to make the PDF password protection.

Following is pom.xml for the dependencies : 

    <dependencies>
           <dependency>
           <groupId>com.itextpdf</groupId>
           <artifactId>itextpdf</artifactId>
          <version>5.2.1</version>
  </dependency>
  <dependency>
       <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.46</version>
    </dependency>

</dependencies>


So most import libraries to use are :

1 . itextpdf-5.2.1.jar 
2 . bcprov-jdk15on-1.46.jar 

Code to implement : 

       

/**
 * @author sachin
 *
 */
public class PdfEncryption {
public static void main(String[] args) {
try {
String outputPdfFile = "/Users/sachin/Desktop/testing.pdf";
String userPassword = "testing_user";
String ownerPassword ="testing_owner"
String pdfContent = "This is the demonstration of the pdf password protection";
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfFile));
writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
document.open();
document.addAuthor("Sachin Srivastava");
document.addCreator("Sachin Srivastava");
document.addSubject("Thanks for your support");
document.addTitle("Please read this");
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(pdfContent));
document.close();
writer.close();
System.out.println("pdf created from content");
} catch (Exception e) {
System.out.println("error occured in creating pdf from content");
}
}
}


Above  code generates a PDF named testing.pdf with the password protection.

Here PDFWriter setEncryption is used to encrypt the pdf using user password byte
array as a first parameter, owner password byte array as a second parameter, 3rd
parameter as the PDF permission(PdfWriter.ALLOW_PRINTING - 2052 ) and 4th is the
encryption type which is of two type

ENCRYPTION_AES_128
ENCRYPTION_AES_256


So enjoy coding with tek9g tips of encrypting PDF and making it password protected.

Wednesday, 16 November 2016

Next higher number with same digits

Finding a next higher number with the same digits is one of the challenging problem to identify a solution with respect to  time space complexity . Any solution which provides in least time and least space would be suitable for the best fit of the solution.

There are multiple solution to this problem :

Solution 1 :

Simplest solution is to find the all permutations of the digits and sort the numbers and then compare with the given number to find next higher number .

Time complexity O(n!) for the solution and not at all suitable for practical cases.It would be worst solution to this problem.

Solution 2 :

Another solution with the O(n) time complexity and O(1) space would be as follow :

       
public static void swap(char[]  charArray, int j , int k){
char temp = charArray[j];
charArray[j] = charArray[k];
charArray[k] = temp;
}
public static void nextHigherInteger(Integer input){
if(input == null || input<=0 ){
return;
}
String s = input.toString();
char[] charArr = s.toCharArray();
int charLength = charArr.length;
int breakPoint = 0;
for (int i = charLength-1; i > 0; i--) {
char last = charArr[i];
char secondLast = charArr[i-1];
if(secondLast < last ){
breakPoint = i-1;
break;
}
if(breakPoint == 0){
System.out.println("This is the highest number");
return;
}
String first = s.substring(0, breakPoint+1);
String second = s.substring(breakPoint+1, charLength);
char[] secondCharArra = second.toCharArray();
Arrays.sort(secondCharArra);//sorting to the second substring
StringBuffer sb2 =new StringBuffer();
sb2.append(first);
for (char c : secondCharArra) {
sb2.append(c);
}          
char[] charArray = sb2.toString().toCharArray();
int j = breakPoint;
int k = ++breakPoint;
while(true){
if(charArray[j] < charArray[k]){
swap(charArray, j, k);
break;
} else {
k++;
}
}
StringBuffer sb3 = new StringBuffer();
for (char c : charArray) {
sb3.append(c);
}  
System.out.println(sb3.toString());
}
public static void main(String[] args) {
//nextHigherInteger(34722641);//34724126
//nextHigherInteger(1234675);//1234756
//nextHigherInteger(23514);//23541
nextHigherInteger(38276);//38627
}

Above mention solution is simple in terms of understanding the logic ,it uses following main points :

1 .  Traverse from tail till the higher sequence is break means from left to right traverse and check that left digit must be higher than right digit , at any point of its less , its a break/pivot point.

2. Divide two substring one for left to the break/pivot point and one for the right of the pivot point.

3. Sort the second string in the ascending order  and compare the first char to rightmost character of first string(x) , if its higher then swap them . If its is less then go for next char of the second string and compare them if its correct then swap it , similarly till the next higher number to  x is found. 

4. Merge first and second string  and your required number would this string.

Time complexity  : O(n) and space O(1) 
Sorting Method : Merge sort of Default Java 


Friday, 14 October 2016

Reversing a Linked List


There are multiple ways of solving this problem  :

1. Using Recursion in the O(n) time & O(n) space complexity: 


 /**
 * @author sachin
 *
 */
public class LinkedListDemo {
static Node head;
static class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
static void printList(Node head){
while(head!=null){
System.out.println(head.data + " ");
head = head.next;
}
}
static void recursiveReverse(Node head)  {
//Base condition
if(head ==null ){
return;
}
recursiveReverse(head.next);
System.out.println(head.data + " ");
}
public static void main(String[] args) {
LinkedListDemo.head = new Node(25);
LinkedListDemo.head.next = new Node(35);
LinkedListDemo.head.next.next = new Node(14);
LinkedListDemo.head.next.next.next = new Node(12);
System.out.println("Original Linked list is :");
LinkedListDemo.printList(head);
System.out.println("Reversed linked list : ");
LinkedListDemo.recursiveReverse(head);
}
}
Output:
Original Linked list is :
25 
35 
14 
12 
Reversed linked list : 
12 
14 
35 
25 

2. Using Iteration  in time O(n) & space O(1) complexity : 

This approach follows takes 3 Nodes   current[head node] , next and previous , head node is looped to move forward and prev node follows it as below :

Before iteration :

head --> 1 --> 2 --> 3 --> 4 --> 5--> null


Node current = head;
Node next = null;
Node prev = null;
//iterate the head node to the end or till the null is found

while(current!=null){
next = current.next;  //get the next node N
current.next=prev;  //next node N assigned the value of prev node
prev = current; //prev node is assigned to current node
current = next; // current node is assigned to next node 
}
head = prev;  //head is assigned to prev node which has the node detail in reverse order 


After iteration :


null <--1 <-- 2 <-- 3 <-- 4 <-- 5  <--- head



  
/**
 * @author sachin
 *
 */
public class LinkedListDemo {
static Node head;
static class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
static Node reverse(Node head){
Node current = head;
Node next = null;
Node prev = null;
while(current!=null){
next = current.next;
current.next=prev
prev = current;
current = next;
}
head = prev;
return head;
}
static void printList(Node head){
while(head!=null){
System.out.println(head.data + " ");
head = head.next;
}
}
public static void main(String[] args) {
LinkedListDemo.head = new Node(25);
LinkedListDemo.head.next = new Node(35);
LinkedListDemo.head.next.next = new Node(14);
LinkedListDemo.head.next.next.next = new Node(12);
System.out.println("Original Linked list is :");
LinkedListDemo.printList(head);
System.out.println("Reversed linked list : ");
head = LinkedListDemo.reverse(head); //getting the head node after reversal
LinkedListDemo.printList(head);
}
}
Output : 

Original Linked list is :
25 
35 
14 
12 
Reversed linked list : 
12 
14 
35 
25 


Enjoy the coding !!!

Tuesday, 11 October 2016

Lambda expression in Java 8


Lambda expressions, also known as closures, function literals, or simply lambdas
Lambda expression is being one of the biggest feature of the Java 8 that are massively increasing the capability  of Java to functional programming . Its use is very simple to use at the same time easy to simple to understand.

Its look like :

     functional interface =   parameter --> expression body  gives output of the expression operation

(arg1, arg2...) -> { body }

(type1 arg1, type2 arg2...) -> { body }

Following are some examples of Lambda expressions.
(int a, int b) -> {  return a + b; }

() -> System.out.println("Lambda Expression unveiled");

(String s) -> { System.out.println(s); }

() -> 30

() -> { return 3.1415 };


  • Lambda expression is being mainly used to define the inline implement of a functional interface which is having only one  method.
  • Lambda expression eliminates the need of anonymous interface and define an inline implementation of the functional interface.
  • Any interface can have a lambda expression associated with it if satisfies the following 3 conditions ->:
  1. Interface must be a functional interface i.e., its should have only one method.
  2. Number of parameters in the lambda expression must match the number of parameters of the functional interface single method.
  3. Return type of the lambda expression must match the return type of single interface method.
  • we can annotate the interface with @FunctionalInterface, a new annotation for Java 8 that says we have a functional interface
  • Just like in the javascript , function are treated as an first order function and are treated as a part of functional programming , same is the lambda expression are treated in the Java8.


In the Javascript function are not mandatory to have a return value and can have only expression body E.g. ,

function mathOperation(a , b){
}

There are 4 type of lambda expressions  is presented as follows :


       
1. With type declaration 
(int a, int b) -> a + b; 
2. Without type declaration
 (a, b) -> a - b; 
3. With return statement along with curly braces
 (int a, int b) -> { return a * b; };

4. Without return statement and without curly braces.
(int a, int b) -> a / b;



  • A lambda expression  is essentially an object , one can assign this object to a variable and pass the lambda expression for other operation. 
Example1

public class LambdaExpression  {
@FunctionalInterface
public interface NumberComparator {
public boolean compare(int a1, int a2);
}
public static void main(String[] args) {
NumberComparator numberComparator = (a1, a2) -> {return a1 > a2;};
boolean result = numberComparator.compare(4, 3);
System.out.println("result=" + result);
}
}
Output: 

result=true


Example2 :  Sorting on the List of a class Employee


/**
 * @author sachin
 *
 */
class Employee{
String name;
Integer age;
Employee(String name,Integer age){
this.name = name;
this.age = age;
}
}
public class LambdaExpression  {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<>();
empList.add(new Employee("John", 23));
empList.add(new Employee("Adam", 26));
empList.add(new Employee("Rollins", 28));
empList.add(new Employee("Richard", 26))
// old way of sorting  on name using anonymous class
System.out.println("--- sorting on the name using anonymous class using comparator --- ");
Collections.sort(empList, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
});
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
// new way of sorting  on name using lambda expression
System.out.println("\n--- sorting on the age using lambda expression with type removing the anonymous class --- ");
//Anonymous Inner class replaced with Lambda expression with type declaration and sorting on age
Collections.sort(empList, (Employee e1 ,Employee e2) -> e1.age.compareTo(e2.age));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
System.out.println("\n--- sorting on the age using lambda expression without type removing the anonymous class --- ");
//Anonymous Inner class replaced with Lambda expression with type declaration and sorting on age
Collections.sort(empList, ( e1 , e2) -> e1.age.compareTo(e2.age));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
System.out.println("\n--- sorting on the name using sort of the List and lambda expression --- ");
//Anonymous Inner class replaced with Lambda expression without type declaration and sorting on name
Collections.sort(empList, (Employee e1 ,Employee e2) -> e1.age.compareTo(e2.age));
empList.sort((e1,e2) -> e1.name.compareTo(e2.name));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
}
}
Output : 
--- sorting on the name using anonymous class using comparator --- 

Adam 26
John 23
Richard 26
Rollins 28
--- sorting on the age using lambda expression with type removing the anonymous class --- 
John 23
Adam 26
Richard 26
Rollins 28
--- sorting on the age using lambda expression without type removing the anonymous class --- 
John 23
Adam 26
Richard 26
Rollins 28
--- sorting on the name using sort of the List and lambda expression --- 
Adam 26
John 23
Richard 26
Rollins 28
------------------------------------------      


Lambda expression is a brilliant feature added in the Java to remove the uses of anonymous class and make a robust feature towards functional programming. Functional interfaces which is another great feature added in the Java makes the lambda expression more useful and easy to understand .

Enjoy the Lambda expression !!!!