Wednesday, June 27, 2018

How do you install Intellij IDEA on Ubuntu?

Problem statement: How do you install intellij IDE on Ubuntu?

$> sudo apt-add-repository ppa:mmk2410/intellij-idea 
$> sudo apt-get update
  • The community edition can then installed with
$> sudo apt-get install intellij-idea-community
  • and the ultimate edition with
$> sudo apt-get install intellij-idea-ultimate

Tuesday, June 26, 2018

Saving data to file using SpringBoot postman

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.boot</groupId>
<artifactId>raja-boot</artifactId>
<version>1.0.1-Release</version>
<packaging>war</packaging>

<name>spring-boot</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
<!-- </dependency> -->

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>

</dependencies>
<build>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2. SpringBootApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.boot"})
public class SpringBootApp {

public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
System.out.println("spring boot application is running");
}
}

3. RestController.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.boot.entity.Student;

@org.springframework.web.bind.annotation.RestController
@RequestMapping("/api")
public class RestController {
@RequestMapping(value = "/ping/", method = RequestMethod.GET)
public String ping() {
  return "successsss !!";
}
@RequestMapping(value = "/create/", method = RequestMethod.POST)
@ResponseBody 
public String create(@RequestBody Student data) throws IOException {
File file = new File("/home/rajar/demo.txt");
FileOutputStream stream = new FileOutputStream(file);
OutputStreamWriter obj = new OutputStreamWriter(stream);
BufferedWriter br  =new BufferedWriter(obj);
br.write(data.getName().toString());
br.append("\n");
br.write(data.getId());
br.close();
  return "<h2>rajjjjjjaaaaaa !!</h2>";
}
}

4. Student.java

import java.io.Serializable;

public class Student implements Serializable {

private String id;
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}

How do you print all elements of a matrix in diagonal order?

Problem statement: 

Print Matrix Diagonally (Diagonal order)

How do you find largest element in an array ?

Problem statement: how do you find the largest element in an array?

Method-I:
  1. public class LargestElementInArray{
  2. public static void main(String[] args) {
  3. int a[] = { 60, 65, 70, 55, 45, 80 };
  4. int max = a[0];
  5.   int length = a.length;
  6. for(int i=0; i<lengthi++){
  7. if(max a[i]){
  8. max = a[i];
  9. }
  10. }
  11. System.out.println(max);
  12. }
  13. }
Output: 80
Time complexity: O(n)

Method-II:
  1. public class LargestElementInArray {
  2. public static void main(String[] args) {
  3. int a[] = { 60, 65, 70, 55, 45, 80 };
  4. int max = a[0];
  5. int length = a.length;
  6. int end = a.length - 1;
  7. for (int i = 0; i < length / 2; i++) {
  8. if (max < a[end]) {
  9. max = a[end];
  10. }
  11. if (max < a[i]) {
  12. max = a[i];
  13. }
  14. }
  15. System.out.println(max);
  16. }
  17. }
Output: 80
Time complexity: O(n/2)

Monday, June 25, 2018

How do you declare, instantiate, initialize and traverse an array?

Problem statement: How will you declare, initialize & traverse an array?
  1. class TestArray {
  2. public static void main(String args[]) {
  3. int a[] = new int[5];// declaration and instantiation.
  4. a[0] = 10;// initialization.
  5. a[1] = 20;
  6. a[2] = 70;
  7. a[3] = 40;
  8. a[4] = 50;
  9. }
  10. }

Longest Palindromic Substring

Problem statement: Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
  1. import java.io.IOException;
  2. public class LongestSubstringPalindrome
  3. {
  4.   public static void main(String[] args) throws IOException
  5.   {
  6.     // String word = "abbcbba";
  7.     String str = "abbagoodteacher";
  8.     System.out.println(longestPalindrome(str));
  9.   }
  10.   public static String longestPalindrome(String s)
  11.   {
  12.     int length = s.length();
  13.     if (s == null || length < 2)
  14.     {
  15.       return s;
  16.     }
  17.     boolean isPalindrome[][] = new boolean[length][length];
  18.     int left = 0;
  19.     int right = 0;
  20.     for (int j = 1; j < length; j++)
  21.     {
  22.       for (int i = 0; i < j; i++)
  23.       {
  24.         boolean isInnerWordPalindrome = isPalindrome[i + 1][j - 1] || j - i <= 2;
  25.         if (s.charAt(i) == s.charAt(j) && isInnerWordPalindrome)
  26.         {
  27.           isPalindrome[i][j] = true;
  28.           if (j - i > right - left)
  29.           {
  30.             left = i;
  31.             right = j;
  32.           }
  33.         }
  34.       }
  35.     }
  36.     return s.substring(left, right + 1);
  37.   }
  38. }
Output: abba

Best time to buy & sell stock

Problem statement: Say you have an array for which the i-th element is the price of a given stock on day i .

If you were only permitted to complete at most one transaction (i.e. buy one &  sell one share of the stock), design an algorithm to find the maximum profit.

Example:
Input:  [7, 3, 6, 7, 2, 8, 5, 6]
Output: 
max difference: 8-2 = 6
  1. public class BuySellStock
  2. {
  3.   public static void main(String[] args)
  4.   {
  5.     int p[] =  { 7, 3, 6, 7, 2, 8, 5, 6 };
  6.     System.out.println(maxProfit(p));
  7.   }
  8.   static int maxProfit(int[] prices)
  9.   {
  10.     int maxProfit = 0;
  11.     int minPrice = Integer.MAX_VALUE;
  12.     for (int i = 0; i < prices.length; i++)
  13.     {
  14.       minPrice = Math.min(minPrice, prices[i]);
  15.       maxProfit = Math.max(maxProfit, prices[i] - minPrice);
  16.     }
  17.     return maxProfit;
  18.   }
  19. }
Output: 6

Sunday, June 24, 2018

How do you do search in an array where difference between adjacent elements is k

Problem statement: How do you do efficient search in an array where difference between adjacent elements is k
  1. public class JumpSearchWithKDiff {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 6, 8, 6, 4, 2, -1, -3 };
  4. int s = -3; // 's' is the element to be searched
  5. int k = 2; // diff. b/w element
  6. int n = a.length; // length of array
  7. System.out.println("Element " + s + " is present at index " + searchAlgo(a, n, s, k));
  8. }
  9. static int searchAlgo(int a[], int n, int s, int k) {
  10. // scan the given array staring from leftmost element
  11. int i = 0;
  12. while (i < n) {
  13. // check if element is found
  14. if (a[i] == s)
  15. return i;
  16. // else jump to diff. b/w current array element & search element
  17. // divided by k We use max here to make sure that i moves at-least one step ahead
  18. i = i + Math.abs(a[i] - s) / k;
  19. // i = i + Math.max(1, Math.abs(a[i] - s) / k);
  20. }
  21. System.out.println("number is " + "not present!");
  22. return -1;
  23. }
  24. }
Output:
Element -3 is present at index 8

How do you do search in an array where difference between adjacent elements is always 1

Problem statement: How do you do efficient search in an array where difference between adjacent elements is always 1
  1. public class JumpSearch {
  2. public static void main(String[] args) {
  3. int a[] = { 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 7, 8, 9, 8, 7, 6, 5};
  4. System.out.println(searchAlgo(a, 7)); // search element is 7
  5. }
  6. // 's' is the element to be searched in array a[0..n-1]
  7. static int searchAlgo(int a[], int s) {
  8. int n = a.length; // length of array
  9. // scan the given array staring from leftmost element
  10. int i = 0; // left first index
  11. while (i < n) {
  12. // check if element is found
  13. if (a[i] == s) {
  14. return i;
  15. }
  16. // else jump to diff. b/w current array element & search element
  17. i = i + Math.abs(a[i] - s);
  18. }
  19. return -1; // element does not found
  20. }
  21. }
Output: 8
Time complexity: less than O(n)

Saturday, June 23, 2018

How do you print Fibonacci series?

Problem statement: How do you print Fibonacci series?

Def: A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
  1. public class FibonacciSeries {
  2. public static void main(String[] args) {
  3. int count = 10;
  4. printFibonacci(count);
  5. }
  6. public static void printFibonacci(int count) {
  7. int a = 0, b = 1, c = 0;
  8. System.out.print(a + " " + b + " ");
  9. for (int i = 2; i < count; i++) {
  10. c = a + b;
  11. a = b;
  12. b = c;
  13. System.out.print(c + " ");
  14. }
  15. }
  16. }
Output: 
0 1 1 2 3 5 8 13 21 34

Method-II:
  1. public class FibonacciSeries {
  2. public static void main(String[] args) {
  3. fibonacci(10); // 10 is count 
  4. }
  5. public static void fibonacci(int n) {
  6. int a[] = new int[n];
  7. a[0] = 0;
  8. a[1] = 1;
  9. System.out.print(a[0] + " " + a[1] + " ");
  10. for (int i = 2; i < n; i++) {
  11. a[i] = a[i - 1] + a[i - 2];
  12. System.out.print(a[i] + " ");
  13. }
  14. }
  15. }
Output:
0 1 1 2 3 5 8 13 21 34

Friday, June 22, 2018

Thursday, June 21, 2018

How do you print Odd Even using Thread ?

Problem Statement: How will print Odd Even using Thread?
OR
How will you print t1 & t2 alternatively using thread?
  1. import java.util.concurrent.atomic.AtomicLong;
  2. class Even extends Thread {
  3. AtomicLong num;
  4. Object lock;
  5. Even(AtomicLong num, Object lock) { // constructor
  6. this.num = num;
  7. this.lock = lock;
  8. }
  9. public void run() {
  10. synchronized (lock) {
  11. while (true) { // infinite loop
  12. if (num.get() % 2 != 0) {
  13. try {
  14. lock.wait();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. } else {
  19. System.out.println("even: " + num);
  20. try {
  21. Thread.sleep(1000);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. num.incrementAndGet();
  26. lock.notifyAll();
  27. }
  28. }
  29. }
  30. }
  31. } // end of Even class

  32. class Odd extends Thread {
  33. AtomicLong num;
  34. Object lock;
  35. Odd(AtomicLong num, Object lock) { // constructor
  36. this.num = num;
  37. this.lock = lock;
  38. }
  39. public void run() {
  40. synchronized (lock) {
  41. while (true) { // infinite loop
  42. if (num.get() % 2 == 0) {
  43. try {
  44. lock.wait();
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. }
  48. } else {
  49. System.out.println("odd: " + num);
  50. try {
  51. Thread.sleep(1000);
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. num.incrementAndGet();
  56. lock.notifyAll();
  57. }
  58. }
  59. }
  60. }
  61. } // end of Odd class

  62. public class EvenOddByThread {
  63. public static void main(String[] args) {
  64. AtomicLong num = new AtomicLong(1);
  65. Object lock = new Object();
  66. Odd odd = new Odd(num, lock);
  67. Even even = new Even(num, lock);
  68. even.start();
  69. odd.start();
  70. }
  71. } // end of EvenOddByThread class
Note: To print t1 & t2 alernatively, just replace the S.O.P. stmt with t1 & t2

Output: 

odd: 1
even: 2
odd: 3
even: 4
odd: 5
even: 6
odd: 7
even: 8
odd: 9
even: 10

Wednesday, June 20, 2018

How do you do binary search in java?

Problem statement: How will you do for binary search in java?
  1. public class BinarySearchExe {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 5, 6, 7, 9, 10 };
  4. int idx = binarySearch(a, 10);
  5. System.out.println(idx);
  6. } // end of main
  7. static int binarySearch(int a[], int key) {
  8. int start = 0, end = a.length - 1;
  9. while (start <= end) {
  10. int mid = (start + end) / 2;
  11. if (key == a[mid]) {
  12. return mid;
  13. } else if (key > a[mid]) {
  14. start = mid + 1;
  15. } else {
  16. end = mid - 1;
  17. }
  18. }
  19. return -1; // if key does not found, return -1
  20. } // end of binarySearch method
  21. }
Output: 6

How do you create tree data structure ?

Problem statement: How will you create tree in java?
  1. /* Class containing left and right child of current
  2. node and data value*/
  3. class Node
  4. {
  5. int data;
  6. Node left, right;

  7. public Node(int data1)
  8. {
  9. data = data1;
  10. left = right = null;
  11. }
  12. }

  13. // A Java program to introduce Binary Tree
  14. class BinaryTree
  15. {
  16. // Root of Binary Tree
  17. Node root;

  18. // Constructors
  19. BinaryTree(int data1)
  20. {
  21. root = new Node(data1);
  22. }

  23. BinaryTree()
  24. {
  25. root = null;
  26. }

  27. public static void main(String[] args)
  28. {
  29. BinaryTree tree = new BinaryTree();

  30. /*create root*/
  31. tree.root = new Node(1);

  32. /* following is the tree after above statement
  33.  
  34.               1
  35.             /   \
  36.           null  null     */

  37. tree.root.left = new Node(2);
  38. tree.root.right = new Node(3);

  39. /* 2 and 3 become left and right children of 1
  40.                1
  41.              /   \
  42.             2      3
  43.           /    \    /  \
  44.         null null null null  */


  45. tree.root.left.left = new Node(4);
  46. tree.root.left.left.right = new Node(9);
  47.         /* 4 becomes left child of 2
  48.                     1
  49.                 /       \
  50.                2          3
  51.              /   \       /  \
  52.             4    null  null  null
  53.            /   \
  54.           null 9
  55.          */
  56. System.out.println(tree.root.right.data);
  57. }
  58. }
Output: 3

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...