Sunday, April 30, 2017

WAP

WAP to check if the string is palindrom ?
        String s="abaa";
        String s_rev = "";
        for (int rev =s.length()-1;rev>=0;rev--){
           s_rev=s_rev+s.charAt(rev);
        }
        if (s.equals(s_rev))
            System.out.println("palindrom");
        else
          System.out.println("not a palindrom");

or

Public boolean is_palindrome(String s, int i, int j){
         while(i<j){
                if(s.charAt(i)!=s.charAt(j)){
                         return false;
                }
                i++;
                j--;
         }
         return true;
}

========================================================================
Given an array of integers, every element appears twice, except for one. Find that single one.
public class Solution {
    public int singleNumber(int[] nums) {
        
        int result = 0;
        for(int i : nums) {
            result ^= i;
        }
         return result;
    }
}
========================================================================WAP to check if the Number is Palindrom?

  1. class PalindromeExample{  
  2.  public static void main(String args[]){  
  3.   int r,sum=0,temp;    
  4.   int n=454;//It is the number variable to be checked for palindrome  
  5.   
  6.   temp=n;    
  7.   while(n>0){    
  8.    r=n%10;  //getting remainder  
  9.    sum=(sum*10)+r;    
  10.    n=n/10;    
  11.   }    
  12.   if(temp==sum)    
  13.    System.out.println("palindrome number ");    
  14.   else    
  15.    System.out.println("not palindrome");    
  16. }  
  17. }  
========================================================================WAP for input string=aabbbccccaaa, maintain the insertion order and output should be like a2b3c5a3


public class CountAlphabets {

    public static void process(String mystring) {
        StringBuilder sb = new StringBuilder();
        char[] mychar = mystring.toCharArray();
        int count = 1;
        for(int i=0; i< (mychar.length)-1;i++) {
            //System.out.println("mychar[p1]: "+mychar[i]+" mychar[p2]: "+mychar[i+1]);
            if(mychar[i] == mychar[i+1]) {
                count = count+1;
                //System.out.println("count: "+count);
            }
            else {
                sb.append(mychar[i]);
                sb.append(count);
                count = 1;
            }
            if(i==(mychar.length)-2) {
                sb.append(mychar[i+1]);
                sb.append(count);
            }
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        process("aabbbcccca");
        process("ggggyyynnnkkkkkk");
        process("aabbcccdef");
        process("abcdefghj");
    }
========================================================================
Print the numbers with same first and last digit
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String s="";
for (int i=0;i<num;i++){
   long leftMost = sc.nextInt();
   long rightMost = sc.nextInt();
   List<Long> res = new ArrayList<>();
   for(long j=leftMost;j<=rightMost;j++){
       s = String.valueOf(j);
       if(s.charAt(0)==s.charAt(s.length()-1)){
           res.add(j);
       }
   }
   System.out.println(res);
}
}
}
=======================================================================
WAP to read a file and sort the content and write into another file.

import java.io.BufferedReader;
   import java.io.FileReader;
   import java.io.FileWriter;
   import java.io.PrintWriter;
   import java.util.ArrayList;
   import java.util.Collections;
   import java.util.List;

    public class sort {

    public static void main(String[] args) throws Exception {

    String inputFile = "test.txt";
    String outputFile = "sort.txt";

    FileReader fileReader = new FileReader(inputFile);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String inputLine;
    List<String> lineList = new ArrayList<String>();
    while ((inputLine = bufferedReader.readLine()) != null) {
        lineList.add(inputLine);
    }
    fileReader.close();

    Collections.sort(lineList);

    FileWriter fileWriter = new FileWriter(outputFile);
    PrintWriter out = new PrintWriter(fileWriter);
    for (String outputLine : lineList) {
        out.println(outputLine);
    }
    out.flush();
    out.close();
    fileWriter.close();

          }
     }
=================================================================================
WAP to do string reverse:
Eg: Same Hello World
i) o/p: dlrow olleh emaS  
[5ways to do this: http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html]
ii) Another WAP to make "World Hello Same"
i) First Program: 
import java.io.*;
import java.util.*;

public class reverseString {
 public static void main(String[] args) {
    String input = "Be in present";
    char[] temparray= input.toCharArray();
    int left,right=0;
    right=temparray.length-1;
    for (left=0; left < right ; left++ ,right--){
     // Swap values of left and right 
     char temp = temparray[left];
     temparray[left] = temparray[right];
     temparray[right]=temp;
    }
    for (char c : temparray)
     System.out.print(c);
    System.out.println();
   }}
o/p: tneserp ni eB

ii)
public class HelloWorld{
     public static void main(String []args){ 
        String word= "Scanner isn't working";
        String revWord="";
        String[] words = word.split(" ");
        for (int i=words.length-1;i>=0;i--){
            revWord = revWord+" "+words[i];
        }
        System.out.println("Reverse Words:"+revWord.trim());
    }
}
o/p: working isn't Scanner
or
Here we reverse the cells, so the performance/speed is doubled than the above approach.

import java.util.Scanner;

public class HelloWorld{

     public static void main(String []args){
        String word= "Scanner isn't working, needs to be checked";
        
        String[] words = word.split(" ");
        int left=0, right= words.length-1;

        for (left=0; left < words.length/2 ; left++ ,right--)
            {
             // Swap values of left and right 
             String temp = words[left];
             words[left] = words[right];
             words[right]=temp;
            }
            
        for (String xyz: words){
            System.out.print(xyz+" ");}
    }
}



}
==============================================================

Determine If String Has All Unique Characters : Java Code With Example

(http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html)

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class HelloWorld {
    
    public static void main (String args[])
    {
        boolean result=false;
        String inputstring="Alve i@wsom";
        System.out.println(inputstring);
        HashSet < Character> uniquecharset= new HashSet();
        for(int i=0;i < inputstring.length();i++)
        {
            result=uniquecharset.add(inputstring.charAt(i));
            if (result == false)
            break;
        }
    System.out.println(result); }
}

==============================================================
Sort without sort method:
  1. package com.Instanceofjava; 
  2. public class SortString {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. String original = "edcba";
  7. int j=0;
  8. char temp=0;
  9.  
  10.   char[] chars = original.toCharArray();
  11.  
  12.   for (int i = 0; i <chars.length; i++) {
  13.  
  14.       for ( j = 0; j < chars.length; j++) {
  15.  
  16.        if(chars[j]>chars[i]){
  17.             temp=chars[i];
  18.            chars[i]=chars[j];
  19.            chars[j]=temp;
  20.        }
  21.  
  22.    }  
  23.  
  24. }
  25.  
  26. for(int k=0;k<chars.length;k++){
  27. System.out.println(chars[k]);
  28. }
  29.  
  30. }
  31.  
  32. }
 In Python:
unsort_list = ["B", "D", "A", "E", "C"]
sort_list = []

while unsort_list:
    smallest = min(unsort_list)
    sort_list.append(smallest)
    unsort_list.pop(unsort_list.index(smallest))

print sort_list

=============================================================Find duplicates elements in list and print the unique list:

def duplicate(input_list):  
        a = input_list
        b= []  
        for i in range(len(a)):
                if a[i] not in b:
                        b.append(a[i])         
       
        return b
        if __name__=='__main__':
                    print duplicate([1,2,3,4,5,4,3,2,'Hello','World','Hello'])

==============================================================

WAP to find maximum sum of continguos Array.

# Python program to find maximum contiguous subarray
# Function to find the maximum contiguous subarray
from sys import maxint
def maxSubArraySum(a,size):
    max_so_far = max_ending_here = 0
    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if max_ending_here < 0:
              max_ending_here = 0  
        elif (max_so_far < max_ending_here):
                               max_so_far = max_ending_here
return max_so_far
If the list contains negative integers, the above code fails, hence below is the code for that:
def maxSubArraySum(a,size):

     

    max_so_far =a[0]

    max_ending_here = a[0]

     
    for i in range(1,size):
        max_ending_here = max(a[i], max_ending_here + a[i])
        max_so_far = max(max_so_far,max_ending_here )
         
    return max_so_far
==============================================================
WAP to find first non-repeative char in given string:
def nonrepchar(word):
        out = []
        for i in range(len(word)):
                if word[i] not in out:
                        out.append(word[i])
        
        print out[0]
        
if __name__ == '__main__':
    nonrepchar("atester")   //prints 'a'

==============================================================
Display the contents of the file in reverse order:
  1. convert the given file into a list.
  2.  reverse the list by using reversed() for line in reversed(list(open(“file-name”,”r”))):          print(line)
==============================================================
LinkedList reversal:
Public static Node Reverse(Node head)
{
 Node current = head;
 Node prevNode = null;
 Node nextNode = null;

 While ( current != null)
 {
  nextNode = current.next;
  current.next = prevNode;
  prevNode = current;
  current = nextNode; 
 }
 return prevNode;

No comments: