Subscribe Us

Showing posts with label Coding. Show all posts
Showing posts with label Coding. 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(N2), 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:

Java Code Snippet

 




Counting duplicate characters

The solution to counting the characters in a string (including special characters such as #, $, and %) implies taking each character and comparing them with the rest. During the comparison, the counting state is maintained via a numeric counter that's increased by one each time the current character is found. There are two solutions to this problem. The first solution iterates the string characters and uses Map to store the characters as keys and the number of occurrences as values. If the current character was never added to Map, then add it as (character, 1). If the current character exists in Map, then simply increase its occurrences by 1, for example, (character, occurrences+1). This is shown in the following code: 

public Map<Character, Integer> countDuplicateCharacters(String str) {

Map<Character, Integer> result = new HashMap<>();

// or use for(char ch: str.toCharArray()) { ... }

for (int i = 0; i<str.length(); i++) {

char ch = str.charAt(i);

result.compute(ch, (k, v) -> (v == null) ? 1 : ++v);

}

return result;

}

Another solution relies on Java 8's stream feature. This solution has three steps. The first two steps are meant to transform the given string into Stream<Character>, while the last step is responsible for grouping and counting the characters. Here are the steps:

 

1. Call the String.chars() method on the original string. This will return IntStream. This IntStream contains an integer representation of the characters from the given string.

2. Transform IntStream into a stream of characters via the mapToObj() method (convert the integer representation into the human-friendly character form).

3. Finally, group the characters (Collectors.groupingBy()) and count them (Collectors.counting()).

The following snippet of code glues these three steps into a single method:

public Map<Character, Long> countDuplicateCharacters(String str) {

Map<Character, Long> result = str.chars()

.mapToObj(c -> (char) c)

.collect(Collectors.groupingBy(c -> c, Collectors.counting()));

return result;

}

Finding the first non-repeated character

There are different solutions to finding the first non-repeated character in a string. Mainly, the problem can be solved in a single traversal of the string or in more complete/partial traversals. In the single traversal approach, we populate an array that's meant to store the indexes of all of the characters that appear exactly once in the string. With this array,simply return the smallest index containing a non-repeated character:

 

private static final int EXTENDED_ASCII_CODES = 256;

...

public char firstNonRepeatedCharacter(String str) {

int[] flags = new int[EXTENDED_ASCII_CODES];

for (int i = 0; i < flags.length; i++) {

flags[i] = -1;

}

for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);

if (flags[ch] == -1) {

flags[ch] = i;

} else {

flags[ch] = -2;

}

}

int position = Integer.MAX_VALUE;

for (int i = 0; i < EXTENDED_ASCII_CODES; i++) {

if (flags[i] >= 0) {

position = Math.min(position, flags[i]);

}

}

return position == Integer.MAX_VALUE ?

Character.MIN_VALUE : str.charAt(position);

}

 

This solution assumes that every character from the string is part of the extended ASCII table (256 codes). Having codes greater than 256 requires us to increase the size of the array accordingly The solution will work as long as the array size is not extended beyond the largest value of the char type, which is Character.MAX_VALUE, that is, 65,535. On the other hand, Character.MAX_CODE_POINT returns the maximum value of a Unicode code point, 1,114,111. To cover this range, we need another implementation based on codePointAt() and codePoints(). Thanks to the single traversal approach, this is pretty fast. Another solution consists of looping the string for each character and counting the number of occurrences. Every second occurrence (duplicate) simply breaks the loop, jumps to the next character, and repeats the algorithm. If the end of the string is reached, then it returns the current character as the first non-repeatable character.

insertion-order map (it maintains the order in which the keys were inserted into the  map) and is very convenient for this solution. LinkedHashMap is populated with characters as keys and the number of occurrences as values. Once LinkedHashMap is complete, it will return the first key that has a value equal to 1. Thanks to the insertion-order feature, this is the first non-repeatable character in the string:

 

public char firstNonRepeatedCharacter(String str) {

Map<Character, Integer> chars = new LinkedHashMap<>();

// or use for(char ch: str.toCharArray()) { ... }

for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);

chars.compute(ch, (k, v) -> (v == null) ? 1 : ++v);

}

for (Map.Entry<Character, Integer> entry: chars.entrySet()) {

if (entry.getValue() == 1) {

return entry.getKey();

}

}

return Character.MIN_VALUE;

}

Reversing letters and words

 

First, let's reverse only the letters of each word. The solution to this problem can exploit the StringBuilder class. The first step consists of splitting the string into an array of words using a white space as the delimiter (Spring.split(" ")). Furthermore, we reverse each word using the corresponding ASCII codes and append the result to StringBuilder. First, we split the given string by space. Then, we loop the obtained array of words and reverse each word by fetching each character via charAt() in reverse order: 

private static final String WHITESPACE = " ";

...

public String reverseWords(String str) {

String[] words = str.split(WHITESPACE);

StringBuilder reversedString = new StringBuilder();

for (String word: words) {

StringBuilder reverseWord = new StringBuilder();

for (int i = word.length() - 1; i >= 0; i--) {

reverseWord.append(word.charAt(i));

}

reversedString.append(reverseWord).append(WHITESPACE);

}

return reversedString.toString();

}

Obtaining the same result in Java 8 functional style can be done as follows:

private static final Pattern PATTERN = Pattern.compile(" +");

...

public static String reverseWords(String str) {

return PATTERN.splitAsStream(str)

.map(w -> new StringBuilder(w).reverse())

.collect(Collectors.joining(" "));

}

Notice that the preceding two methods return a string containing the letters of each word reversed, but the words themselves are in the same initial order. Now, let's consider another method that reverses the letters of each word and the words themselves. Thanks to the built-in StringBuilder.reverse() method, this is very easy to accomplish:

public String reverse(String str) {

return new StringBuilder(str).reverse().toString();

}

 

Share:

R - Programming

 



Features Of R : 

1) R is a well-developed, simple and effective programming language which includes decision making , flow control, recursive, functions input and output methods

2) R has an effective data handling and storage facility which is important for statistical analysis.

3) R Provides a variety of operators for calculations on arrays, lists, vectors and matrices.

4) R provides a large, coherent and integrated collection of packages and tools for data analysis including mathematical symbols. Dynamic and interactive graphics are available through additional packages 

5) R and its libraries implement a wide variety of statistical and graphical techniques, including  linear and non linear modelling, classical statistical tests, time - series analysis, classification,clustering and others

6) R is easily extensible through function and extensions. R community is noted for its active contribution in terms of packages. For computationally intensive tasks, C, C++ and Fortran code van be linked and called at run time. Advanced users can write C/C++, Java , .NET or Python code to manipulate R objects directly

7) Since R was  inherited from a language called S , R has stronger objective-oriented programming facilities than  most statistical computation languages 

Identifiers:

The unique name given to variable like function or object is known as an identifier . Following are the rules for naming an identifier.

a)     Identifier can be a combination of letters, digits, period, and underscore(_).

b)     It must start with a letter or a period. If it starts with a period, it cannot be followed by a digit.

c)     Reserved word in R cannot be used as identifiers

Examples of some valid identifiers are: total, sum, .date, .date.of.birth,sum_of_two

Example of some invalid identifiers are : tot@l,2um, _prod, TRUE, .0wl

Earlier version of R used underscore  (_) as an assignment operator. So, the period (.) was used extensively in variable names having multiple words.

Constants :

Constants or literals, as the name suggest, are entities whose values cannot be altered. Basic type of constants are numeric and character constants. They are built-in constants also.  

All numbers fall under this category. They can be of type integer, double, or complex, We can check the type of constants by typeof() function.

Variables:

A variable provides us with named storage that our programs manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many R objects. A valid variable name consists of letters, numbers and the dot or underline characters. The rule for naming a variable is same as that of any identifiers which is already discussed above.

The variable can be assigned values leftward, rightward and equal to operator. The values of the variables can be printed using print () or cat ()function. The cat()  function combines multiple items into a continuous print output.

Operators :

R has several operator to perform tasks arithmetic, logical and bitwise operations. R provides following types of operators . They are

a)     Arithmetic operator

b)     Relational Operator

c)     Logical Operator

d)     Assignment Operator

e)     Miscellaneous Operator

Arithmetic operator:

These operators are used to carry out mathematical operations, like addition, subtraction, multiplication, division. The arithmetic operators are applied for vectors. Even if we give a single value, it is considered as a vector with length one.

 

  

Relational operator :

Relational operator are used to compare between values. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.

 

 

Logical operator :


 Logical operator are applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is Boolean value.

Operator

Description

!

Logical Not, Takes each element of the vector and gives the opposite logical value

&

Element wise logical And. It combines each element of the first vector with corresponding element of the second vector and gives an output TRUE if both the values are  TRUE.

&&

Logical AND. It takes first element of both the vectors and gives  TRUE only if both elements are TRUE

|

Element-wise logical OR. It combines each element of the first vector with the corresponding element of the second vector and gives an output TRUE if one of the elements is TRUE

||

Logical OR. It takes first element of both the vectors and gives an output TRUE if one of the element is TRUE

 

Assignment Operator :

These operators are used to assign values to variables or vectors. The operators <- and = can be used almost interchangeably to assign values to a variables in the same environment.

The <<- operator is used for assigning values to variables in the parent environments

Operators

Description

<-,<<-,=

Leftward assignment

->,->>

Rightward assignment

 

 

Miscellaneous operator :

These operator are used for specific purpose. They are not used for mathematical or logical computation.

Operators

Description

:

Colon. It creates a range of numbers in sequence for a vector.

%in%

This operator is used to check whether an element belongs to a vector or not. The result will be a Boolean value either TRUE or FLASE.

%*%

This operator is used to multiply a matrix with its transpose

 

 

Strings:

Strings are created in R by writing any value within a pair of single quote or double quotes. However, internally R stores every strings within  double quotes, even if we create them with single quote. The quotes at the beginning and end of a string should be both double quotes or both single quotes. They cannot be mixed. Another feature of string is that double quotes can be inserted into a string staring and ending with single quote. Similarly single quote can be inserted into a string a staring and ending with double quotes.

Reading String :

We can read string from keyboard using the readLines () function . It lets the user to enter one-line string at the terminal . The syntax as follows :

a <- readLines("stdin", n=1);



Share:

HTML & Javascript

 





Four Arithmetic Operation with the help of HTML & Javascript 


<!DOCTYPE html>

<html>

<head>

<title>Four function calculators</title>

<script language="javascript">

function Addition()

 {

  var x,y,c,c1,z,sp, c2,c3;

  x=parseInt(document.calculator.x.value);

  y=parseInt(document.calculator.y.value);

  c=document.getElementById("c");

  c1=document.getElementById("c1");

  sp=document.getElementById("sp");

  c2=document.getElementById("c2");

  c3=document.getElementById("c3");

  if(c.checked==true)

  {

  z=x+y;

  //alert(z);

  sp.innerHTML=z;

  c1.checked=false;

  c2.checked=false;

  c3.checked=false;

  }


// body...

}

function Substraction()

 {

  var x,y,c,c1,z,sp,c2,c3;

  x=parseInt(document.calculator.x.value);

  y=parseInt(document.calculator.y.value);

  c=document.getElementById("c");

  c1=document.getElementById("c1");

  sp=document.getElementById("sp");

  c2=document.getElementById("c2");

  c3=document.getElementById("c3");

  if(c1.checked==true)

  {

  z=x-y;

  //alert(z);

  sp.innerHTML=z;

  c.checked=false;

  c2.checked=false;

  c3.checked=false;



  }


// body...

}

function multiplication()

{

var x,y,c,c1,z,sp,c2,c3;

x=parseInt(document.calculator.x.value);

y=parseInt(document.calculator.y.value);

c=document.getElementById("c");

c1=document.getElementById("c1");

sp=document.getElementById("sp");

c2=document.getElementById("c2");

  c3=document.getElementById("c3");

if (c2.checked==true) 

{

z=x*y;

//alert(z);

sp.innerHTML=z;

c.checked=false;

c1.checked=false;

c3.checked=false;

}

}

function division()

{

var x,y,c,c1,z,sp,c2,c3;

x=parseInt(document.calculator.x.value);

y=parseInt(document.calculator.y.value);

c=document.getElementById("c");

c1=document.getElementById("c1");

sp=document.getElementById("sp");

c2=document.getElementById("c2");

  c3=document.getElementById("c3");

if (c3.checked==true) 

{

z=x/y;

//alert(z);

sp.innerHTML=z;

c.checked=false;

c1.checked=false;

c2.checked=false;

}

}

</script>

</head>

<body>

<form name="calculator">

Enter first Number<input type="text" name="x"><br>

Enter second number<input type="text" name="y"><br>

Answer:<span id="sp"></span>

<input type="checkbox" name="c" id="c" value="add" onclick="Addition();">Add

<input type="checkbox" name="c1" id="c1" value="sub" onclick="Substraction();">Sub

<input type="checkbox" name="c2" id="c2" value="multiplication" onclick="multiplication();">multi

<input type="checkbox" name="c3" id="c3" value="division" onclick="division();">div


</body>

</html>

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

Labels

Blogger templates