Subscribe Us

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Cyclic Sort (First Level)

 

Cyclic Sort (easy)

Problem Statement 

We are given an array containing ‘n’ objects. Each object, when created, was assigned a unique number from 1 to ‘n’ based on their creation sequence. This means that the object with sequence number ‘3’ was created just before the object with sequence number ‘4’.

Write a function to sort the objects in-place on their creation sequence number in O(n)O(n) and without any extra space. For simplicity, let’s assume we are passed an integer array containing only the sequence numbers, though each number is actually an object.

Example 1:

Input: [3, 1, 5, 4, 2]
Output: [1, 2, 3, 4, 5]

Example 2:

Input: [2, 6, 4, 3, 1, 5]
Output: [1, 2, 3, 4, 5, 6]

Example 3:

Input: [1, 5, 6, 4, 3, 2]
Output: [1, 2, 3, 4, 5, 6]

Solution 

As we know, the input array contains numbers in the range of 1 to ‘n’. We can use this fact to devise an efficient way to sort the numbers. Since all numbers are unique, we can try placing each number at its correct place, i.e., placing ‘1’ at index ‘0’, placing ‘2’ at index ‘1’, and so on.

To place a number (or an object in general) at its correct index, we first need to find that number. If we first find a number and then place it at its correct place, it will take us O(N^2)O(N​2​​), which is not acceptable.

Instead, what if we iterate the array one number at a time, and if the current number we are iterating is not at the correct index, we swap it with the number at its correct index. This way we will go through all numbers and place them in their correct indices, hence, sorting the whole array.

Let’s see this visually with the above-mentioned Example





Here is the code in Following Language
a) Python (Problem 4)
b) Java  (Problem 4)
c) C++ (Problem 3)
d) Javascript (Problem 2) 

Time complexity #

The time complexity of the above algorithm is O(n). Although we are not incrementing the index i when swapping the numbers, this will result in more than ‘n’ iterations of the loop, but in the worst-case scenario, the while loop will swap a total of ‘n-1’ numbers and once a number is at its correct index, we will move on to the next number by incrementing i. So overall, our algorithm will take O(n) + O(n-1) which is asymptotically equivalent to O(n).

Space complexity #

The algorithm runs in constant space O(1).




Share:

Encapsulating Object Creation in Java




Encapsulating Object Creation Polymorphism enables code to be more abstract. When your code references an interface instead of a class, it loses its coupling to that class and becomes more flexible in the face of future modifications. This use of abstraction was central to many of the techniques of the previous chapters. Class constructors are the one place where such abstraction is not possible. If you want to create an object, you need to call a constructor; and calling a constructor is not possible without knowing the name of the class. This chapter addresses that problem by examining the techniques of object caching and factories. These techniques help the designer limit constructor usage to a relatively small, well-known set of classes, in order to minimize their potential liability.

Object Caching

Suppose you want to write a program that analyzes the status of a large number of motion-detecting sensors, whose values are either “on” or “off.” As part of that program, you write a class Sensors that stores the sensor information in a list and provides methods to get and set individual sensor values.

public class Sensors

{

 private List L = new ArrayList<>();

 public Sensors(int size)

 {

 for (int i=0; i<size;i++)

{

L.add(new Boolean(false));

}

public boolean getSensor(int n)

{

 Boolean val = L.get(n);

return val.booleanValue();

}

public void setSensor(int n, boolean b)

 {

L.set(n, new Boolean(b));

}

}

This code creates a lot of Boolean objects: the constructor creates one object per sensor and the setSensor method creates another object each time it is called. However, it is possible to create far fewer objects. Boolean objects are immutable (that is, their state cannot be changed), which means that Boolean objects having the same value are indistinguishable from each other. Consequently, the class only needs to use two Boolean objects: one for true and one for false. These two objects can be shared throughout the list.

Following code shows a revision of Sensors that takes advantage of immutability. This code uses the variables off and on as a cache. When it needs a Boolean object for true it uses on; and when it needs a Boolean object for false it uses off.

 

public class Sensors

{

private List L = new ArrayList<>();

private static final Boolean off = new Boolean(false);

 private static final Boolean on = new Boolean(true);

public Sensors(int size)

{

 for (int i=0; i<size;i++)

{

L.add(off);

}

public boolean getSensor(int n)

 {

 Boolean val = L.get(n);

return val.booleanValue();

 }

 

public void setSensor(int n, boolean b)

{

Boolean val = b ? on : off; L.set(n, val);

 }

 }

 

This use of caching is a good idea, but in this case it is limited to the Sensors class. If you want to use Boolean objects in another class, it could be awkward to share the cached objects between the two classes. Fortunately, there is a better way—the Boolean class has caching built into it.

Singleton Classes

One important use of caching is to implement singleton classes. A singleton class is a class that has a fixed number of objects, created when the class is loaded. It does not have a public constructor, so no additional objects can be created. It is called “singleton” because the most common situation is a class having a single instance. For example, if the Java designers had made the Boolean constructor private (which would have been a good idea) then Boolean would be a singleton class. On the other hand, Integer cannot be a singleton class, even if its constructor were private, because its valueOf method creates new objects when needed. The Java enum syntax simplifies the creation of singleton classes and is the preferred way of writing singletons.

 

Writing Boolean as an Enum

 public enum Boolean

 {

 TRUE(true), FALSE(false);

private boolean value;

 private Boolean(boolean b)

 {

value = b;

}

public boolean booleanValue()

 {

return value;

}

public static Boolean valueOf(boolean b)

{

return (b ? TRUE : FALSE);

 }

 ...

}

Note that the syntactic differences are incredibly minor. The main difference concerns the definitions of the constants TRUE and FALSE, which omit both the declaration of their type and their call to the Boolean constructor. The values inside the parentheses denote the arguments to the constructor. That is, the statement TRUE(true), FALSE(false); is equivalent to the two statements

public static final Boolean TRUE = new Boolean(true);

public static final Boolean FALSE = new Boolean(false);

 

Conceptually, an enum is a class that has no public constructors, and therefore no objects other than its public constants. In all other respects an enum behaves like a class.

Beginners are often unaware of the correspondence between enums and classes because an enum is typically introduced as a named set of constants. For example, the following enum defines the three constants

Speed.SLOW, Speed.MEDIUM, and Speed.FAST:

public enum Speed {SLOW, MEDIUM, FAST};

This enum is equivalent to the class definition of the following code. Note that each Speed constant is a reference to a Speed object having no functionality of interest.

 

public class Speed

 {

public static final Speed SLOW = new Speed();

public static final Speed MEDIUM = new Speed();

 public static final Speed FAST = new Speed();

 private Speed() { }

}

 

As with classes, an enum constructor with no arguments and no body (such as the constructor for Speed) is called a default constructor. Default constructors can be omitted from enum declarations just as they can be omitted from class declarations. Because the constants in an enum are objects, they inherit the equals, toString, and other methods of Object. In the simple case of the Speed enum, its objects can do nothing else. The elegant thing about the Java enum syntax is that enum constants can be given as much additional functionality as desired. The default implementation of an enum’s toString method is to return the name of the constant. For example, the following statement assigns the string “SLOW” to variable s.

String s = Speed.SLOW.toString(); 

Share:

Abstract of LAN chat application (using Java)

 







ABSTRACT

 

LAN chat application is one of easiest way to chat with a your friends through LAN. No internet connection is needed. The only thing which requires is server IP address and you will be able to connect to others members through LAN . It can help you to talk to your friends even you both do not have internet connection. As it is based on LAN. LAN i.e.  local area network which connect different client to each other and also client to main server. So we have used the same concept here we are connecting two client or client and server with each other and by providing the IP address we can talk with each other.

 

On the other hand file sharing application  is also implemented where a user can upload a file or download a file. We are providing the path to the directory where we have stored our file to the user who wants to download particular file.

 


 

INTRODUCTION

The growth of the Internet has led to new and faster forms of communication. There are now programs that allow users to communicate in real-time with one or more people. These instant messaging tools are commonly referred to as IRC (Internet Relay Chat). Some of these programs can be downloaded for free.

LAN chat is one the same way can be used to talk to your friend in your circle .All you have to do is to provide his IP address and then you both will get connect to each other and then you can talk.It is helpful because if you have any problem while solving something you do not have  to go to his room and to meet him and  you can talk to him on chat if you both are connected to each other and can get solution of your problem .Chat application is one of the most useful software which is used by every business to communicate with his employers if he is out of station.

File sharing  on the other hand is good tool to share those file which your friend wants from you or any other file which can be useful for other. The user can see this file after login to system and can download this file .It is one of the easiest way as it doesn’t require much knowledge for sharing and downloading.

OVEVIEW

The LAN  chat application which we have implemented contain following things :-

1.     LOGIN

2.     CHAT

3.     JOIN CHAT ROOM

4.     UPLOAD FILE

5.     DOWNLOAD FILE

LOGIN   :

 

 

·        In computer security, a login or logon is the process by which individual access to a computer system is controlled by identification of the user using credentials provided by the user.

·        A user can log in to a system to obtain access and can then log out or log  off (perform a logout / logoff) when the access is no longer needed.

·        To log out is to close off one's access to a computer system after having previously logged in.

·        The registered user  needs to provide his username and password to authenticate his account.

·        After successful  login user will allow to chat and upload and download file .

 

THERE ARE TWO MODULES IN IT:-

      1.ADMIN LOGIN

      2.USER LOGIN

 

ADMIN MODULE :-

1.Add new user :: Admin can add a new user.Whether to allow any one to create a account or not depends on user to this chat application .

 

2.View user :Admin has got the right to check the personal details of the user .He can see all user details .

 

3.Delete user :Admin can also delete user who is abusing  other member and who is not following the rules .

 

4.Update chatroom: Admin can update chat room  and can also limit a chat room a  fixed number if he finds that there is too much crowd in chat room .

 

5.Delete files:If admin finds that particular file is bad or containing  virus that he can delete that file.

 

 

USER MODULE

1.Profile update : User can update the information given by him such as name and about me .he can change it as many times as he want to there is no restriction in it.

 

2.Chat room : User can join any chat room he wish to join  and there is no restriction in it.

3.File upload : User can upload file from the client Machine to server machine.

4.File download User can download file from the server Machine to client machine.

 

 

CHAT

 

After logged in user is allowed to chat with each other in a group or in private. This help user to get any information or solution of their problem  and also to share his knowledge with others.

 

You can also connect with your friends only if you want to talk to him privately .

 

Same is in case of file sharing a user can download and upload file easily by just clicking the file .This is very easy process and any one can easily upload and download file.

 

JOIN CHAT ROOM

In this you can connect to particular room which is currently running or have at least 1 user in it .This type of room are made to share particular information. You can join any chat room if room is available and can talk to other people who are logged in right now .

 

UPLOAD FILE

This will help you to upload a particular file from your computer to a server which other can easily download.To upload a file a user must be logged in only then he can upload a file .A file should not be bad other wise admin has the right to delete it .

DOWNLOAD FILE

In this a user can download a particular file he wants to. For this a user just have to log in and then go to path where all files are available and then he has to click on that file and it will prompt a message to save a file to particular location and in this way you can download and save a file.

 

 


 

 

TECHNOLOGIES USED

 

Front end as: Eclipse helios

Back end as:  Mysql

Database:  Mysql

Querying language:   Sql

Forms: Jsp , Java servlet

External library  :  Apache common.fileupload , Apache.commons.io

 

REQUIREMENTS

 

System Requirements:

Operating System: Microsoft® Windows® XP/Vista/window7/linux

Processor: 1 Ghz

Memory: 512 MB RAM

Hard Disk Space: 45 MB Available HDD Space

Video Card: 3D graphics accelerator equivalent to GF6200 or higher

Sound Card: 16-bit Sound Card

DirectX® Version: DirectX® 9.0c

 


 

 

TABLES USED :

 

LOGIN

loginid

VARCHAR2(30)

 

name

VARCHAR2(30)

password

VARCHAR2(30)

 

email

VARCHAR2(30)

 

type

VARCHAR2(30)

 

 

 

 

 

 

 

 

 

CHAT ROOMS:

 

roomname

VARCHAR2(30)

 

roomdesc

VARCHAR2(30)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 




SHARED FILES:

 

fileName

VARCHAR2(30)

 

contenttype

VARCHAR(30)

loginid

VARCHAR2(30)

 

 

 

 

Share:
Powered by Blogger.

Ad Code

Responsive Advertisement

Ad Code

Responsive Advertisement

Featured post

Search This Blog

Recently added book names

THE HTML AND CSS WORKSHOP   | MICROSOFT POWER BI COOKBOOK   | MongoDB in Action, 2nd Edition  | ADVANCED DEEP LEARNING WITH PYTHON   | Cracking Codes with Python An Introduction to Building and Breaking  | Moris Mano Degital Design 3rd Edition  | Beginning App Development with Flutter by Rap Payne  |react hooks in Action - John Larsen   | Artificial Intelligence A Modern Approach Third Edition Stuart Russel  | Data Structures and Algorithms - Narasimha Karumanchi   | Thomas S.M. - PostgreSQL High Availability Cookbook - 2017  | Gunnard Engebreth PHP 8 Revealed Use Attributes the JIT Compiler   | ICSE Class X Computer Application Notes   | INTERNET OF THINGS PROJECTS WITH ESP32   | 100 aptitude trick(102pgs)s   | OBJECT_ORIENTED_PROGRAMMING Question & Answer   | C questions and answer   | Full_Book_Python_Data_Structures_And_Algorithm   | Jira 8 Administration Cookbook Third Edition  | KALI LINUX WIRELESS PENETRATION TESTING BEGINNERS GUIDE THIRD EDITION - Cameron Buchanan, Vivek Ramachandran  HTML5 & javascript By :- Jeanine Meyer   | Python For Beginners Ride The Wave Of Artificial Intelligence   | HackingTheXbox   | Introduction to Algorithms 3rd.Edition - (CLRS)   | The C++ Programming Language - Bjarne Stroustrup   | Modern C++ Programming Cookbook - Marius Bancila   | Java The Complete Reference Eleventh Edition   Data_Communications and Networking 4th Ed Behrouz A Forouzan   | DevOps with Kubernetes - Hideto Saito   | The-Linux-Command-Line-A-Complete-Introduction   | Assembly Language for X86 Processors KIP R. Irvine   | Effective_Modern_C++ - Scott Meyer

Contact Form

Name

Email *

Message *

Followers

Mobile Logo Settings

Mobile Logo Settings
image

Computer Training School Regd. under Govt. of West Bengal Society Act 1961

Header Ads Widget

Responsive Advertisement

Hot Widget

random/hot-posts

Recent in Sports

Popular Posts

Most Popular

Popular Posts

Labels

Blogger templates