October 29, 2018

Bricks Game in Java

/**
 * Patlu and Motu works in a building construction, they have to put some number of bricks N from one place to another, and started doing their work. They decided , they end up with a fun challenge who will put the last brick.

They to follow a simple rule, In the i'th round, Patlu puts i bricks whereas Motu puts ix2 bricks.

There are only N bricks, you need to help find the challenge result to find who put the last brick.
Input:

First line contains an integer N.

Output:

Output "Patlu" (without the quotes) if Patlu puts the last bricks ,"Motu"(without the quotes) otherwise.

Constraints:

 */
package com.hackerearth.basicprograming;

import java.util.Scanner;

/**
 * @author consumerfed
 *
 */
public class BricksGame {

/**
* @param args
*/
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int noOfBricks = sc.nextInt();
String currentPerson = "P";
int step = 1;
int intialValue = 1;
int bricksMoved = 0;

while ((noOfBricks - bricksMoved) > 0) {
if ((step % 2) != 0) {
currentPerson = "P";
bricksMoved = bricksMoved + intialValue;
} else {
currentPerson = "M";
bricksMoved = bricksMoved + (intialValue * 2);
intialValue = intialValue + 1;
}
step = step + 1;
}

System.out.println(currentPerson);
}

}

Output

13 bricks are there :
Patlu Motu
1 2
2 4
3 1 ( Only 1 remains)
Hence, Motu puts the last one.

E Maze In Program Logic in java

/**
 * Ankit is in maze. The command center sent him a string which decodes to come out from the maze. He is initially at (0, 0). String contains L, R, U, D denoting left, right, up and down. In each command he will traverse 1 unit distance in the respective direction.
 * For example if he is at (2, 0) and the command is L he will go to (1, 0).
 *
 * SAMPLE INPUT : LLRDDR
 * SAMPLE OUTPUT : 0 -2
 *
 */
package com.hackerearth.basicprograming;
import java.util.Scanner;
/**
 * @author consumerfed
 *
 */
public class EMazeIn {

/**
* @param args
*/
public static void main(String[] args) {
int x = 0;
int y = 0;
Scanner sc = new Scanner(System.in);
String traverse = sc.nextLine();
for(int i=0;i<traverse.length();i++) {
char movement = traverse.charAt(i);
switch (movement) {
case 'L':
x =x -1;
break;
case 'D':
y = y -1;
break;
case 'R':
x = x + 1;
break;
case 'U':
y = y + 1;
break;

default:
break;
}
}
System.out.println( x + " "+y );
}
}

SAMPLE INPUT : LLRDDR

SAMPLE OUTPUT : 0 -2

October 23, 2018

To find the area of circle & Multiplication Table in Java

/**
 * To find the area of circle  & Multiplication Table
 */
package com.cfed.lambda;

import java.util.Scanner;

/**
 * @author consumerfed
 *
 */
public class ExampleJava {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
 
  ExampleJava ex = new ExampleJava();
  Scanner sc = new Scanner(System.in);
  System.out.println(" Enter the numbers ( to find the mul table upto 5 )");
  int mulNumb = sc.nextInt();
  ex.multiplicationTable(mulNumb);
  System.out.println(" Find the area of a circle ( Enter the radius)");
  float radius = sc.nextFloat();
  System.out.println(" The area of the circle with "+radius+" is "+ex.findAreaOfCircle(radius));;

 }



 private double findAreaOfCircle(float radius) {
  // TODO Auto-generated method stub
  double area = Math.PI * Math.sqrt(radius);
  return area;
 }



 private void multiplicationTable(int mulNumb) {
  // TODO Auto-generated method stub
  for(int i =1; i<=mulNumb; i++) {
   for(int j=1; j<=5;j++) {
    System.out.println(i+" x "+j+" = "+(i*j));
   }
  }
 }

}


Output

 Enter the numbers ( to find the mul table upto 5 )

4

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15

4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20

 Find the area of a circle ( Enter the radius)

3

 The area of the circle with 3.0 is 5.441398092702653

October 22, 2018

Working with lambda expression in java 8

Lambda Expression in java 8



Source code will be available in github also


Function Interface 1



package com.cfed.lambda;
interface NumericTest {
int computeTest(int n);
}


/**
 *  Function Interface 2
 */
package com.cfed.lambda;

/**
 * @author consumerfed
 *
 */
public interface StringManip {

public String operate(String s);

}


/**
 * sample lambda experssion in java 1.8
 *
 */
package com.cfed.lambda;

public class MainClass {

public static void main(String args[]) {

NumericTest square  = (value) -> (value * value);
System.out.println(" the object square returns :"+square.computeTest(5));

NumericTest cube  = (value) -> (value * value * value);
System.out.println(" the object cube returns :"+cube.computeTest(5));

StringManip concatStr = (val) -> (val+val);
System.out.println(" String concat is "+concatStr.operate("itsection"));

StringManip reverseStr = (str) ->{
String result = "";

for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);

return result;

};

System.out.println(" The reverse of the string is :"+reverseStr.operate("consumerfed"));
}

}

Output

 the object square returns :25
 the object cube returns :125
 String concat is itsectionitsection
 The reverse of the string is :defremusnoc

October 17, 2018

Angular JS and Servlet Sample web application



index.jsp

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="getdata();"> Click </button>
<h2>NSTYLE APPOINMENT DETAILS</h2>

<table style="width:100%" ng-if="records.length > 0">
  <tr>
    <th>Client Name</th>
    <th>Date</th>
    <th>Shop</th>
     <th>Service Name</th>
      <th>Mobile Nuber</th>
  </tr>


  <tr ng-repeat="record in records" >
    <td>{{record.clientName}}</td>
    <td>{{record.appointmentDate}}</td>
    <td>{{record.shopName}}</td>
    <td>{{record.serviceName}}</td>
    <td>{{record.mobileNumber}}</td>
  </tr>


</table>



<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
  $scope.records = [];
  $scope.getdata=function(){

    $http({
        method : "POST",
        url : "http://localhost:8080/NStyleSample/ApplicationServlets"
    }).then(function mySuccess(response) {
    $scope.records = response.data;
    }, function myError(response) {
      //  $scope.myWelcome = response.statusText;
    });

  }

});
</script>

</body>
</html>


Servlets

package com.nstyle.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.nstyle.models.AppointmentModels;
import com.nstyle.utils.AppointmentUtils;

/**
 * Servlet implementation class ApplicationServlets
 */
public class ApplicationServlets extends HttpServlet {
private static final long serialVersionUID = 1L;


private AppointmentUtils appointmentUtils = null;
/**
* @see HttpServlet#HttpServlet()
*/
public ApplicationServlets() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println(" INSIDE SERVLET ");
appointmentUtils = new AppointmentUtils();
List<AppointmentModels> appointments = appointmentUtils.getValue();
ObjectMapper mapper = new ObjectMapper();
String respMess = mapper.writeValueAsString(appointments);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(respMess);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}


Utils classes

package com.nstyle.utils;

import java.util.ArrayList;
import java.util.List;

import com.nstyle.models.AppointmentModels;

public class AppointmentUtils {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}
public List<AppointmentModels> getValue(){
List<AppointmentModels> appointmentList = null;
appointmentList = new ArrayList<AppointmentModels>();
for(int i =1; i<=5;i++){
AppointmentModels appointment = new AppointmentModels();
appointment.setClientName("Client "+i);
appointment.setAppointmentDate("2018-10-02");
appointment.setMobileNumber("050197390"+i);
appointment.setServiceName("Service "+i);
appointment.setShopName("Shop "+i);
appointmentList.add(appointment);
}
return appointmentList;
}

}

Web.xml ( Deployment descriptor)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>NStyleSample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ApplicationServlets</display-name>
    <servlet-name>ApplicationServlets</servlet-name>
    <servlet-class>com.nstyle.servlets.ApplicationServlets</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ApplicationServlets</servlet-name>
    <url-pattern>/ApplicationServlets</url-pattern>
  </servlet-mapping>
</web-app>

github link

https://github.com/nijeshcfed/NStyleSample

October 14, 2018

Course for self study of data science (Machine Learning)


Hi

We know how difficult it can be to choose a good course,
because there are so many available!
We suggest starting closer to the beginning of the list if you're just starting to explore data science.

https://datamovesme.com/2018/08/01/favorite-moocs-for-data-scientists/

October 13, 2018

Java program to implement Queue

A stack is a collection where insertion and deletion happens in the same end ( LIFO)
In Queue an insertion or updates should occurs on one end , that we called tail/rear
Any removal should happens on the other end, that we called front/head

Operations available with Queue

* insertion is called enqueue operation ( push)
* deletion is called dequeue operation (pop)
* peek() to return the front element
* isEmpty()
* isFull()




/**
 * Implementing queue in java using
 *
 * Here i wrote a sample program to implement queue in java
 *
 */
package com.belazy.algorithm;

/**
 * @author consumerfed Triveni kozhikode
 *
 */
public class QueueADT {

private Object[] queueArray = null;
private int MAX_SIZE = 5;
int front = 0; // head of the queue
int rear = 0; // tail
int size = 0;

public QueueADT() {
queueArray = new Object[MAX_SIZE];
}

public void enqueue(Object value) {
if (!isFull()) {
queueArray[rear] = value;
rear = rear - 1;
if (rear < 0) {
rear = MAX_SIZE - 1;
}
size = size + 1;
System.out.println(" value :"+value + " front :"+front + "rear : "+rear);
} else {
System.out.println(" The Queue is full ");
}

}

 public Object dequeue() { Object obj = null; if (isEmpty()) { System.out.println(" The Queue is empty "); } else { obj = queueArray[front]; queueArray[front] = null; front = front - 1; if (front < 0) { front = MAX_SIZE - 1; } size = size - 1; System.out.println(" value :"+obj + " front :"+front + "rear : "+rear); System.out.println(" The element removed is "+obj); } return obj; }

public void peek() {
if (!isEmpty())
System.out.println(" The front element is " + queueArray[front]);
}

private boolean isEmpty() {
if (size == 0) {
return true;
}
return false;

}

private boolean isFull() {
if (size == MAX_SIZE) {
return true;
}
return false;
}

public void showElements() {
int i = 0;
for (Object obj : queueArray) {
System.out.println(i + " th position element is " + obj);
i++;
}
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

QueueADT queueADT = new QueueADT();
queueADT.enqueue(new Integer(1));
queueADT.enqueue(new Integer(2));
queueADT.enqueue(new Integer(3));
queueADT.enqueue(new Integer(4));
queueADT.enqueue(new Integer(5));
queueADT.enqueue(new Integer(6));

queueADT.peek();

// queueADT.showElements();

queueADT.dequeue();

queueADT.peek();

// queueADT.showElements();
queueADT.enqueue(new Integer(6));
queueADT.peek();

}

}


Output

 value :1 front :0rear : 4
 value :2 front :0rear : 3
 value :3 front :0rear : 2
 value :4 front :0rear : 1
 value :5 front :0rear : 0
 The Queue is full
 The front element is 1
 value :1 front :4rear : 0
 The element removed is 1
 The front element is 2
 value :6 front :4rear : 4
 The front element is 2


October 11, 2018

Example for an immutable class in java

/**
 *  Example for immutable class
 *  setting class as final implies that the class cannot be extended
 */
package com.belazy.algorithm;

/**
 * @author vinod aravind
 *
 */
public final class Employee {

private final String firstName;
private final String lastName;

public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
   
public String getFirstName(){
return firstName;
}

public String getLastName(){
return lastName;
}


}


Make the class as final - means class should not be extended
member variables as private final - means the value should not be changed

Final keyword in java

The value of  final variables could not be changed, But it can be initialized  through a constructor once

The final methods could not be override

The final class could not be extended

October 08, 2018

How to check whether the strings are anagram or not

/**
 * An anagram of a string is another string that contains same characters, only the order of characters can be different.
 */
package com.belazy.algorithm;

import java.util.Arrays;

/**
 * @author rahul eswar
 *
 */
public class Anagrams {

/**
* @param args
*/
public static void main(String[] args) {
String s = "SAVE";
String d = "VASE";
Anagrams anagram = new Anagrams();
boolean b = anagram.isAnagram(s,d);
System.out.println(" answer is "+b);
boolean j = anagram.isAnagram2(s,d);
System.out.println(" answer is "+b);
}

private boolean isAnagram2(String s, String d) {
char[] c = s.toCharArray();
char[] e = d.toCharArray();
Arrays.sort(c);
Arrays.sort(e);
System.out.println(c);
System.out.println(e);
return Arrays.equals(c, e);
}

private boolean isAnagram(String s, String d) {
boolean isAnagram = false;
if(s.length()!=d.length()){
System.out.println(" Not ");
}else{
for(int i =0; i<s.length();i++){
char c = s.charAt(i);
System.out.print(" comapring "+c+" & "+d);
if(d.contains(String.valueOf(c))){
System.out.println("--> OK");
isAnagram = true;
continue;
}else{
System.out.println("--> NOT OK");
isAnagram = false;
break;
}
}
}
return isAnagram ;
}
}


Output

 comapring S & VASE--> OK
 comapring A & VASE--> OK
 comapring V & VASE--> OK
 comapring E & VASE--> OK
 answer is true
AESV
AESV
 answer is true



Singleton class example in java

/**
 * In the Singleton class, when we first time call getInstance() method,
 *  it creates an object of the class and return it to the variable. 
 *  Since getInstance() is static, it is changed from null to some object.
 *   Next time, if we try to call getInstance() method,
 *    since single_instance is not null, it is returned to the variable,
 *     instead of instantiating the Singleton class again. 
 *     This part is done by if condition
 */
package com.belazy.algorithm;

/**
 * @author ravi shankar mullath
 * 
 */
public class SingletonClass {

private static SingletonClass singleton = null;
public String s = null;

/**
* I made default constructor as private
*/
private SingletonClass() {
s = "sachin tendulkar";
}

/**
* @param args
*/
public static SingletonClass getInstance() {
if (null == singleton)
singleton = new SingletonClass();
return singleton;
}

}


/**
 * 
 */
package com.belazy.algorithm;

/**
 * @author belazy
 *
 */
public class MainClass {

/**
* @param consumerfed kozhikode
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonClass x = SingletonClass.getInstance();
SingletonClass y = SingletonClass.getInstance();
SingletonClass z = SingletonClass.getInstance();
x.s = x.s.toUpperCase();
System.out.println(y.s);

}

}

Output


SACHIN TENDULKAR



Explanation


Here we made the default constructor as private. so this constructor cannot be access from outside the class. So i restricted created objects out side from singleton class.

A new instance of the class can be created only through getInstance() method
SingletonClass x = SingletonClass.getInstance();
While creating an instance it will check whether the instance is already created or not.






October 06, 2018

Java Example for Word Count

/**
 * Word count in java
 *
 * Using regular expression for split by space
 */
package com.belazy.algorithm;
/**
 *
 * @author Murali Krishnan
 *
 */
public class WordCount {

/**
* @param regex
*/
public static void main(String[] regex) {
String s = "I always value my    friends";
// split by single space
String[] sw = s.split("\\s");
// + indicates one or more
String[] wc = s.split("\\s+");
System.out.println(sw.length);
System.out.println(wc.length);
}
}

How to add big integers

/**
 * How to parse big numbers
 */
package com.belazy.algorithm;
/**
 *
 * @author vishnu prasad varma
 *
 */

public class StringToInt {
public static void main(String arg[]){
String s = "1234567";
String d = "23232323";
Double a = new Double(s);
Double b = new Double(d);
System.out.println(a.intValue() + b.intValue());
}

}

How to Reverse an array in java

/**
 * Java Interview Question 
 * Reversing an array 
 */
package com.belazy.javaprograming;

/**
 * @author 
 *
 */
public class ReverseArray {

/**
* @param args
*/
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7};
int[] b = new int[a.length];
int r = a.length;
for(int i=0; i<a.length; i++){
r--;
b[r] = a[i];
}
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
}
}

Facebook comments