Printing Pyramid Shape in Java

Problem:

Print the shape seen below.
                                       


Solution:

public class Pyramid
{
  public static void main (String[] agrs)
  {
    int MAX = 7;
    for (int i =1;i<=MAX;i++)
    {
      for (int j =MAX;j>i;j--)
      {
        System.out.print("   ");
      }
      
      for (int k =0;k<i-1;k++)
      {
        System.out.print(i-k+ "  ");
      }
      
      for (int j =MAX;j>MAX;j--)
      {
        System.out.print("   ");
      }
      
      for (int k =0;k<i;k++)
      {
        System.out.print(k+1+ "  ");
      }
      System.out.println();
    }
  }
}
Read More

Printing Pascal's Triangle in Java

Problem:

Print the shape seen below.


Solution:

public class Pyramid
{
  public static void main (String[] agrs)
  {
    int MAX = 7;
    int temp =1;
    for (int i =0;i<=MAX;i++)
    {
      temp =1;

      for (int j =MAX;j>i;j--)
      {
        System.out.print("\t");
      }
      
      for (int k =0;k<=2*(i-1)+2;k+=2)
      {
        System.out.print((temp) + "\t");
        temp+= temp;
      }
      temp/=2;

      for (int j =MAX;j>MAX;j--)
      {
        System.out.print("\t");
      }
      for (int k =0;k<=2*(i-1);k+=2)
      {
        temp/=2;
        System.out.print((temp) + "\t");
      }
      System.out.println();
    }
  }
}
Read More

Difference between Checked and Unchecked exceptions in Java

Java distinguishes between checked exceptions and unchecked exceptions. This distinction is important, because the Java compiler enforces a catch-or-declare requirement for checked exceptions. An exception’s type determines whether it’s checked or unchecked. All exception types that are direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in your program’s code. Examples of unchecked exceptions include ArrayIndexOutOfBoundsExceptions (discussed in Chapter 7) and ArithmeticExceptions (shown in Fig. 11.3). All classes that inherit from class Exception but not class RuntimeException are considered to be checked exceptions. Such exceptions are typically caused by conditions that are not under the control of the program — for example, in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked.

The compiler checks each method call and method declaration to determine whether
the method throws checked exceptions. If so, the compiler verifies that the checked exception is caught or is declared in a throws clause. We show how to catch and declare checked exceptions in the next several examples. Recall from Section 11.3 that the throws clause specifies the exceptions a method throws. Such exceptions are not caught in the method’s body. To satisfy the catch part of the catch-or-declare requirement, the code that generates the exception must be wrapped in a try block and must provide a catch handler for the checked-exception type (or one of its superclass types). To satisfy the declare part of the catch-or-declare requirement, the method containing the code that generates the exception must provide a throws clause containing the checked-exception type after its parameter list and before its method body. If the catch-or-declare requirement is not satisfied, the compiler will issue an error message indicating that the exception must be caught or declared. This forces you to think about the problems that may occur when a method that throws checked exceptions is called.

Unlike checked exceptions, the Java compiler does not check the code to determine

whether an unchecked exception is caught or declared. Unchecked exceptions typically can be prevented by proper coding. For example, the unchecked ArithmeticException exception can be avoided if the method ensures that the denominator is not zero before attempting to perform the division. Unchecked exceptions are not required to be listed in a method’s throws clause—even if they are, it’s not required that such exceptions be caught by an application.
Read More

How to Create your Own Exception in Java

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}
Methods that can potentially throw or propagate this exception must declare it:
public void calculate(int i) throws FooException, IOException;
... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}
You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).
Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}
Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}
Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.
The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.
Read More

Creating a Product Code Validator in Java

Problem:

Write a program that asks the user to enter a product code starting with the form of: NNNNL, where N denotes a number and L a letter. Keep asking the user for a product number until the user enters "XXX". If N > 2000 and L = B, the code is blacklisted and considered as banned.

The main point of this product validator is to be able to handle exceptions in a robust manner. Thus, you are expected to handle two exceptions manually: IndexOutOfBoundsException and NumberFormatException.

At the end of the program, print the total number of attempts, valid codes and banned codes.


Output:

Enter a product code (XXX to quit):
1900G
Enter a product code (XXX to quit):
2500B
Enter a product code (XXX to quit):
1000R
Enter a product code (XXX to quit):
190G
Code of improper length.
Enter a product code (XXX to quit):
190RG
Region is not numeric.
Enter a product code (XXX to quit):
XXX
Total # attempts: 5
# valid codes: 3
# banned codes: 1


Solution:

import java.util.Scanner;
 public class ProductCodes {
     public static void main(String[] args)
     {    
         String code;
         Scanner scan = new Scanner(System.in);
         char city;
         int region, valid = 0, banned = 0,total = 0;
          
         System.out.println("Enter a product code (XXX to quit): ");
         code = scan.nextLine();
          
         while (!code.equals("XXX"))
         {
         try {
             total++;
             city = code.charAt(4);
             region = Integer.parseInt(code.substring(0,4));
             valid++;
             if (city == 'B' && region >= 2000)
                 banned++;
         } catch (StringIndexOutOfBoundsException e) {
             System.out.println("Code of improper length.");
         } catch (NumberFormatException e ) {
             System.out.println("Region is not numeric.");
         } finally {
              
         }
         System.out.println("Enter a product code (XXX to quit): ");
         code = scan.nextLine();
     }
         System.out.println("Total # attempts: " + total);
         System.out.println(" # valid codes: " + valid);
         System.out.println(" # banned codes: " + banned);
     }        
 }
Read More

How to Input and Output Characters and Symbols in Eclipse

  1. Go to Windows » Preferences
    image
  2. Click on General » Workspace

    image
  3. Alter the text file encoding from Default(Cp1252) to UFT-8

    image
  4. That’s it! Click OK and you’re done.
Read More

how to copy files between windows and linux

clip_image002

The user logs in to winscp370 by providing the appropriate hostname, username, and password and then press Login (Figure g).

 

A vertically divided window will appear showing the Windows directories and files on the left and those on the Linux server on the right (Figure h).

clip_image003clip_image006clip_image004

Figure h. WinSCP

If the user needs to copy a file (or more) from one side to another, he/she just selects them and drag them from the destination side to the other one, and press Copy.

Read More

How to login in linux server

To log in to Linux server, the Windows user should enter to a program called putty, specify the appropriate host name and port number (Figure a), and press OK. Then, once the Linux window appears, he/she should enter his/her username and password on the Linux server (Figure b). After logging in is successful, the user can execute many commands against the Linux server.

Figure a. putty

clip_image002

Figure b. Linux log in

clip_image004

 

Below appear some basic Linux commands:

ls : views files (hidden files are not viewed)

ls–la: views all files (hidden, unhidden, and directories -in another color-)

mkdir : creates a new directory (example: the command mkdir xyz creates a new

directory named xyz )

rm : removes a file (example: the command rm abc removes the file named abc )

rm –r: removes a directory (example: the command rm -r xyz removes the directory named xyz )

mv: renames a file (example: the command mv abc xyz renames the file abc to xyz)

pwd : outputs the present working directory

cd: returns to user's home directory

cd ../ : changes current directory one step back

cd /user/abc: changes current directory to path: /usr/abc

Read More

Escaping HTML Special Characters method in Java

Description:

Source code for the Html Escape class, for escaping text on the fly, using Java.
The Html Escape tool for Java, escapes all characters, known to cause problems on Html pages.
The escaped result is compatible with pages encoded in ISO-8859-X and UTF-8.


The two main methods of the HtmlEscape class are:

escape(String)
Which escapes everything, including new line and returns the escaped result

escapeTextArea(String)
Which escapes everything, except new line, for use in textarea or wysiwyg editors.

Code:

package net.htmlescape; 

/** 
* HtmlEscape in Java, which is compatible with utf-8 
* @author Ulrich Jensen, http://www.htmlescape.net 
* Feel free to get inspired, use or steal this code 
* and use it in your own projects. 
* License: 
* You have the right to use this code in your own 
* project or publish it on your own website. 
* If you are going to use this code, please include 
* the author lines. Use this code at your own risk. 
* The author does not warrant or assume any legal 
* liability or responsibility for the accuracy, 
* completeness or usefulness of this program code. 
*/ 

public class HtmlEscape { 

  private static char[] hex={'0','1','2','3','4','5','6',
                        '7','8','9','a','b','c','d','e','f'}; 

  /** 
   * Method for html escaping a String, for use in a textarea 
   * @param original The String to escape 
   * @return The escaped String 
   */ 
  public static String escapeTextArea(String original) 
  { 
    return escapeSpecial(escapeTags(original));     
  } 
   
  /** 
   * Normal escape function, for Html escaping Strings 
   * @param original The original String 
   * @return The escape String 
   */ 
  public static String escape(String original) 
  { 
    return escapeSpecial(escapeBr(escapeTags(original))); 
  } 
   
  public static String escapeTags(String original) 
  { 
    if(original==null) return ""; 
    StringBuffer out=new StringBuffer(""); 
    char[] chars=original.toCharArray(); 
    for(int i=0;i<chars.length;i++) 
    { 
      boolean found=true; 
      switch(chars[i]) 
      { 
        case 60:out.append("&lt;"); break; //< 
        case 62:out.append("&gt;"); break; //> 
        case 34:out.append("&quot;"); break; //" 
        default:found=false;break; 
      } 
      if(!found) out.append(chars[i]); 
       
    } 
    return out.toString(); 
     
  } 

  public static String escapeBr(String original) 
  { 
    if(original==null) return ""; 
    StringBuffer out=new StringBuffer(""); 
    char[] chars=original.toCharArray(); 
    for(int i=0;i<chars.length;i++) 
    { 
      boolean found=true; 
      switch(chars[i]) 
      { 
        case '\n': out.append("<br/>"); break; //newline 
        case '\r': break; 
        default:found=false;break; 
      } 
      if(!found) out.append(chars[i]); 
       
    } 
    return out.toString(); 
  } 
   
  public static String escapeSpecial(String original) 
  { 
    if(original==null) return ""; 
    StringBuffer out=new StringBuffer(""); 
    char[] chars=original.toCharArray(); 
    for(int i=0;i<chars.length;i++) 
    { 
        boolean found=true; 
      switch(chars[i]) { 
        case 38:out.append("&amp;"); break; //& 
        case 198:out.append("&AElig;"); break; //Æ 
        case 193:out.append("&Aacute;"); break; //Á 
        case 194:out.append("&Acirc;"); break; // 
        case 192:out.append("&Agrave;"); break; //À 
        case 197:out.append("&Aring;"); break; //Å 
        case 195:out.append("&Atilde;"); break; //à
        case 196:out.append("&Auml;"); break; //Ä 
        case 199:out.append("&Ccedil;"); break; //Ç 
        case 208:out.append("&ETH;"); break; //Р
        case 201:out.append("&Eacute;"); break; //É 
        case 202:out.append("&Ecirc;"); break; //Ê 
        case 200:out.append("&Egrave;"); break; //È 
        case 203:out.append("&Euml;"); break; //Ë 
        case 205:out.append("&Iacute;"); break; //Í 
        case 206:out.append("&Icirc;"); break; //Π
        case 204:out.append("&Igrave;"); break; //Ì 
        case 207:out.append("&Iuml;"); break; //Ï 
        case 209:out.append("&Ntilde;"); break; //Ñ 
        case 211:out.append("&Oacute;"); break; //Ó 
        case 212:out.append("&Ocirc;"); break; //Ô 
        case 210:out.append("&Ograve;"); break; //Ò 
        case 216:out.append("&Oslash;"); break; //Ø 
        case 213:out.append("&Otilde;"); break; //Õ 
        case 214:out.append("&Ouml;"); break; //Ö 
        case 222:out.append("&THORN;"); break; //Þ 
        case 218:out.append("&Uacute;"); break; //Ú 
        case 219:out.append("&Ucirc;"); break; //Û 
        case 217:out.append("&Ugrave;"); break; //Ù 
        case 220:out.append("&Uuml;"); break; //Ü 
        case 221:out.append("&Yacute;"); break; //Ý 
        case 225:out.append("&aacute;"); break; //á 
        case 226:out.append("&acirc;"); break; //â 
        case 230:out.append("&aelig;"); break; //æ 
        case 224:out.append("&agrave;"); break; //à 
        case 229:out.append("&aring;"); break; //å 
        case 227:out.append("&atilde;"); break; //ã 
        case 228:out.append("&auml;"); break; //ä 
        case 231:out.append("&ccedil;"); break; //ç 
        case 233:out.append("&eacute;"); break; //é 
        case 234:out.append("&ecirc;"); break; //ê 
        case 232:out.append("&egrave;"); break; //è 
        case 240:out.append("&eth;"); break; //ð 
        case 235:out.append("&euml;"); break; //ë 
        case 237:out.append("&iacute;"); break; //í 
        case 238:out.append("&icirc;"); break; //î 
        case 236:out.append("&igrave;"); break; //ì 
        case 239:out.append("&iuml;"); break; //ï 
        case 241:out.append("&ntilde;"); break; //ñ 
        case 243:out.append("&oacute;"); break; //ó 
        case 244:out.append("&ocirc;"); break; //ô 
        case 242:out.append("&ograve;"); break; //ò 
        case 248:out.append("&oslash;"); break; //ø 
        case 245:out.append("&otilde;"); break; //õ 
        case 246:out.append("&ouml;"); break; //ö 
        case 223:out.append("&szlig;"); break; //ß 
        case 254:out.append("&thorn;"); break; //þ 
        case 250:out.append("&uacute;"); break; //ú 
        case 251:out.append("&ucirc;"); break; //û 
        case 249:out.append("&ugrave;"); break; //ù 
        case 252:out.append("&uuml;"); break; //ü 
        case 253:out.append("&yacute;"); break; //ý 
        case 255:out.append("&yuml;"); break; //ÿ 
        case 162:out.append("&cent;"); break; //¢ 
        default: 
          found=false; 
          break; 
      } 
      if(!found) 
      { 
        if(chars[i]>127) { 
          char c=chars[i]; 
          int a4=c%16; 
          c=(char) (c/16); 
          int a3=c%16; 
          c=(char) (c/16); 
          int a2=c%16; 
          c=(char) (c/16); 
          int a1=c%16; 
          out.append("&#x"+hex[a1]+hex[a2]+
                              hex[a3]+hex[a4]+";");     
        } 
        else 
        { 
          out.append(chars[i]); 
        } 
      } 
    }   
    return out.toString(); 
  } 
   
} 
Read More

JFileChooser java example

Problem:

Create java gui app that allows the user to pick picture
and text files only and displays them respectively.




Solution:

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileFilter;

public class JFileChooserapp extends JFrame {

 
 private JMenuBar bar;
 private JMenu fileMenu;
 private JMenuItem openMenuItem;
 private JEditorPane contentArea;
 private JScrollPane scrollPane;
 private File selectedFile;
 private String[] okExtensions = {"png", "gif", "tiff", "jpg", "txt"};
 
 public JFileChooserapp() {
  super("JFileChooser Demo");
  
  bar = new JMenuBar();
  setJMenuBar(bar);
  
  fileMenu = new JMenu("File");
  fileMenu.setMnemonic('f');
  
  openMenuItem = new JMenuItem("Open");
  openMenuItem.setMnemonic('o');
  openMenuItem.addActionListener(new ActionListener() {
   
   @Override 
   public void actionPerformed(ActionEvent e) {
    selectedFile = getFile();
    if(selectedFile !=null)
     displayFile(selectedFile);
   }

  });
  
  fileMenu.add(openMenuItem);
  bar.add(fileMenu);
  setJMenuBar(bar);
  
  contentArea = new JEditorPane();
  contentArea.setEditable(false);
  scrollPane = new JScrollPane(contentArea);
  
  Container contentPane = getContentPane();
  contentPane.add(scrollPane);
  
  setExtendedState(JFrame.MAXIMIZED_BOTH);
  setVisible(true);
  
  
 }
 
 private File getFile() {
  
  File output = null;
  
  JFileChooser fileChooser = new JFileChooser();
  fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  fileChooser.setFileFilter(new FileFilter() {

   @Override
   public String getDescription() {
   String description = "";
   for (String ext : okExtensions) 
    description += "*." + ext + " ";
   return description;
   }
   
   @Override
   public boolean accept(File f) {
    for(String ext: okExtensions)  
     if (f.getName().toLowerCase().endsWith(ext)) 
     return true;
    return false;
   }

   
  
  });
  
  int result = fileChooser.showOpenDialog(this);
  if (result == JFileChooser.APPROVE_OPTION) {
    output = fileChooser.getSelectedFile();
    if ( output == null || !output.exists()) output = null;
  }
  return output;
  }

 private void displayFile(File file) {
 
  String fileName = file.getName();
  int lastIndexOfDot = fileName.lastIndexOf('.');
  String extension  = fileName.substring(lastIndexOfDot+1);
  boolean isImage = true;
  if (extension.equalsIgnoreCase("txt")) isImage= false;
  
  URL fileUrl = null;
  try {
   fileUrl = file.toURI().toURL();
  } catch (MalformedURLException e) {
   return;
  }
  
  if (isImage) {
   contentArea.setContentType("text/html");
   contentArea.setText("<html><title>Image</title><img src=" + 
   fileUrl + " /></html>");
   
  } else {
   try {
    contentArea.setContentType("text/plain");
    contentArea.setPage(fileUrl);
   } catch (IOException e) {
    return;
   }
  }
  
  
  
 }
 
 
 
 public static void main(String[] args) {
  JFileChooserapp demo = new JFileChooserapp();
  demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
 }
 
 
 
 
 
 
 
 
 
 
 
 
 
}
Read More

Introduction to Polymorphism in Java

If I ask someone to put together a top-ten list of the most important working underlying principles for an object-oriented software development application, most likely polymorphism will make it at the top of list. Polymorphism is an extremely important principle of object-oriented software development.

To truly understand polymorphism, we need to explore one of the blueprints upon which polymorphism is actually built: binding. Think of binding as this piece that makes polymorphism bits.

But what do I actually mean by binding? Binding, if you like, is a commitment(decision) to execute a certain and particular piece of code, and that decision will be either made by the compiler or by the interpreter machine, during the execution of the code. When I say binding, I'm binding method invocation (A particular method definition). Now consider, the two types of binding in JAVA:

1) Early binding: If binding occurs by the compiler, then we talk about and refer to it as early binding (In other words, I had to do that binding before even executing that piece of code.)

Example:
Consider overloading a method, when you overload a method, you have the same method name but different set of parameters, consider the example below:
 int sum(int a , int b) {  
 return a + b;  
 }  
 int sum(int a , int b, int c) {  
 return a + b + c;  
 }  
Let's invoke this piece of code by calling: sum(1,2). Which one of the two versions you think will be executed? The first one. Why? Because you can count the number of parameters, identify the version that will be activated and be put in practice. So I'm here invoking sum(1,2) and I know which version will be called, but I need to need to link/connect that statement in appropriate method definition. Who would do the linking in your thinking? Can the compiler do it? Yes. The compiler actually will do the selection. So when it comes to calling overloaded methods, the compiler can make a commitment to execute a particular piece of code. The compiler is smart and can simply count the number of parameters to determine which version of the method should be executed or invoked actually. When dealing with overloaded methods, compiler selects the appropriate methods, this method selection strategy or procedure is called early binding. EARLY BINDING is called when handling OVERLOADED methods.


2) Late Binding: If binding occurs by the interpreter, then talk about and refer to it as call it late binding. Another name for late binding is dynamic binding. Late binding is used when a polymorphic reference is used. A polymorphic reference fits the definition of polymorphism itself. The meaning of the polymorphism itself actually means having many shapes or having many forms, incarnations. So a polymorphic reference will fit that definition and eventually it will embody that definition in the sense that a polymorphic reference is an object reference variable.

Example:
Consider overriding a method, when you override a method, you have a reference pointed twice, consider the example below:
 class Shape{  
   public void draw(){  
   System.out.println(“Draw a shape.”);  
   }  
 }  
 class Circle extends Shape{  
   public void draw(){  
   System.out.println(“Draw a circle.”);  
   }  
 }  
 class Test{  
   public static void main(String[] args){  
   Shape sh;   
   sh=new Circle(); //That's a polymorphic reference  
   sh.move(); //Print: "Draw a shape."  
   sh=new Shape();  
   sh.move(); //Print: "Draw a circle"  
   }  
 }  
It should be noted that in the first call to draw(), the reference type is Shape and the object being referenced is Circle. So, when a call to draw() is made, Java waits until runtime to determine which object is actually being pointed to by the reference.  In this case, the object is of the class Circle. So, the draw() method of Circle class will be called. In the second call to draw(), the object is of the class Shape. So, the draw() method of Shape will be called. Because we used a polymorphic reference to call a method, late binding takes place. Let me rephrase this: I will have to wait until the program runs before I will be able to determine which version of the method will be used. Interpreter will do the decision why? Because in this case the compiler cannot do it.it doesn't have the appropriate knowledge to make the appropriate decision, so it will be up to the interpreter to identify the method that should be executed. Late binding is less efficient then early binding because it involves making a decision during the execution of your code that will harm and degrade the performance of your programs in terms of running: amount of time to complete a task. There is a word called overhead associated with late binding: late binding is acceptable because of the flexibility offered by polymorphic references. Flexibility is the main key. This is our main target.

Keep In Mind:
Early binding or early polymorphism in Java is achieved by method overloading. Remember example 1.

Later binding or later polymorphism in Java is achieved by method overriding. Remember example 2.



Read More

How to download any vine video from your browser

I'm going to avoid any introductions, here is a straight forward solution.

1. Go to Google Chrome

2. Open your vine video, for example: https://vine.co/v/MaBKAD13T2m

3. Add view-source:https://vine.co/v/MaBKAD13T2m before the link.

4. Click on Ctrl+F.

5. Search for contentURL in the search tab. 

6. You should see something like this.

7. Copy the link in blue.

8. Go to Internet Download Manager, if you're on a MacBook go to iGetter

9. Click on Add URL. The link should automatically appear.

10. After you click OK, something like this will appear, and you will be able to download your vine video.

Read More

List of All important java methods

/*
* Shared code for solutions to Project Euler problems
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.math.BigInteger;
final class Library {
        
        // Returns the reverse of the given string.
        public static String reverse(String s) {
                return new StringBuilder(s).reverse().toString();
        }
        
        
        // Tests whether the given string is a palindrome.
        public static boolean isPalindrome(String s) {
                return s.equals(reverse(s));
        }
        
        
        // Tests whether the given integer is a palindrome in decimal.
        public static boolean isPalindrome(int x) {
                return isPalindrome(Integer.toString(x));
        }
        
        
        // Returns floor(sqrt(x)).
        public static int sqrt(int x) {
                if (x < 0)
                        throw new IllegalArgumentException("Square root of negative number");
                int y = 0;
                for (int i = 32768; i != 0; i >>>= 1) {
                        y |= i;
                        if (y > 46340 || y * y > x)
                                y ^= i;
                }
                return y;
        }
        
        
        // Returns floor(sqrt(x)).
        public static long sqrt(long x) {
                if (x < 0)
                        throw new IllegalArgumentException("Square root of negative number");
                long y = 0;
                for (long i = 1L << 31; i != 0; i >>>= 1) {
                        y |= i;
                        if (y > 3037000499L || y * y > x)
                                y ^= i;
                }
                return y;
        }
        
        
        // Tests whether x is a perfect square.
        public static boolean isSquare(int x) {
                if (x < 0)
                        return false;
                int sqrt = Library.sqrt(x);
                return sqrt * sqrt == x;
        }
        
        
        // Returns x to the power of y.
        public static int pow(int x, int y) {
                if (y < 0)
                        throw new IllegalArgumentException("Negative exponent");
                int z = 1;
                for (int i = 0; i < y; i++) {
                        if (Integer.MAX_VALUE / z < x)
                                throw new ArithmeticException("Overflow");
                        z *= x;
                }
                return z;
        }
        
        
        // Returns x^y mod m.
        public static int powMod(int x, int y, int m) {
                if (x < 0)
                        throw new IllegalArgumentException("Negative base not handled");
                if (y < 0)
                        throw new IllegalArgumentException("Reciprocal not handled");
                if (m <= 0)
                        throw new IllegalArgumentException("Invalid modulus");
                
                // Exponentiation by squaring
                int z = 1;
                while (y != 0) {
                        if ((y & 1) != 0)
                                z = (int)((long)z * x % m);
                        x = (int)((long)x * x % m);
                        y >>>= 1;
                }
                return z;
        }
        
        
        // Returns x^-1 mod m. Note that x * x^-1 mod m = x^-1 * x mod m = 1.
        public static int reciprocalMod(int x, int m) {
                if (m < 0 || x < 0 || x >= m)
                        throw new IllegalArgumentException();
                
                // Based on a simplification of the extended Euclidean algorithm
                int y = x;
                x = m;
                int a = 0;
                int b = 1;
                while (y != 0) {
                        int z = x % y;
                        int c = a - x / y * b;
                        x = y;
                        y = z;
                        a = b;
                        b = c;
                }
                if (x == 1)
                        return (a + m) % m;
                else
                        throw new IllegalArgumentException("Reciprocal does not exist");
        }
        
        
        // Returns n!.
        public static BigInteger factorial(int n) {
                if (n < 0)
                        throw new IllegalArgumentException("Factorial of negative number");
                BigInteger prod = BigInteger.ONE;
                for (int i = 2; i <= n; i++)
                        prod = prod.multiply(BigInteger.valueOf(i));
                return prod;
        }
        
        
        // Returns n choose k.
        public static BigInteger binomial(int n, int k) {
                return factorial(n).divide(factorial(n - k).multiply(factorial(k)));
        }
        
        
        // Returns the largest non-negative integer that divides both x and y.
        public static int gcd(int x, int y) {
                while (y != 0) {
                        int z = x % y;
                        x = y;
                        y = z;
                }
                return x;
        }
        
        
        // Tests whether the given integer is prime.
        public static boolean isPrime(int x) {
                if (x < 0)
                        throw new IllegalArgumentException("Negative number");
                if (x == 0 || x == 1)
                        return false;
                else if (x == 2)
                        return true;
                else {
                        if (x % 2 == 0)
                                return false;
                        for (int i = 3, end = sqrt(x); i <= end; i += 2) {
                                if (x % i == 0)
                                        return false;
                        }
                        return true;
                }
        }
        
        
        // Returns a Boolean array 'isPrime' where isPrime[i] indicates whether i is prime, for 0 <= i <= n.
        // For a large batch of queries, this is faster than calling isPrime() for each integer.
        // For example: listPrimality(100) = {false, false, true, true, false, true, false, true, false, false, ...}.
        public static boolean[] listPrimality(int n) {
                if (n < 0)
                        throw new IllegalArgumentException("Negative size");
                boolean[] prime = new boolean[n + 1];
                if (n >= 2)
                        prime[2] = true;
                for (int i = 3; i <= n; i += 2)
                        prime[i] = true;
                // Sieve of Eratosthenes
                for (int i = 3, end = sqrt(n); i <= end; i += 2) {
                        if (prime[i]) {
                                for (int j = i * i; j <= n; j += i << 1)
                                        prime[j] = false;
                        }
                }
                return prime;
        }
        
        
        // Returns all the prime numbers less than or equal to n, in ascending order.
        // For example: listPrimes(100) = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ..., 83, 89, 97}.
        public static int[] listPrimes(int n) {
                if (n < 0)
                        throw new IllegalArgumentException("Negative size");
                boolean[] isPrime = listPrimality(n);
                int count = 0;
                for (boolean b : isPrime) {
                        if (b)
                                count++;
                }
                int[] primes = new int[count];
                for (int i = 0, j = 0; i < isPrime.length; i++) {
                        if (isPrime[i]) {
                                primes[j] = i;
                                j++;
                        }
                }
                return primes;
        }
        
        
        // Returns the number of integers in the range [1, n] that are coprime with n.
        // For example, totient(12) = 4 because these integers are coprime with 12: 1, 5, 7, 11.
        public static int totient(int n) {
                if (n <= 0)
                        throw new IllegalArgumentException("Totient of non-positive integer");
                int p = 1;
                for (int i = 2, end = Library.sqrt(n); i <= end; i++) { // Trial division
                        if (n % i == 0) { // Found a factor
                                p *= i - 1;
                                n /= i;
                                while (n % i == 0) {
                                        p *= i;
                                        n /= i;
                                }
                                end = Library.sqrt(n);
                        }
                }
                if (n != 1)
                        p *= n - 1;
                return p;
        }
        
        
        // Returns an array 'totients' where totients[i] == totient(i), for 0 <= i <= n.
        // For a large batch of queries, this is faster than calling totient() for each integer.
        public static int[] listTotients(int n) {
                if (n < 0)
                        throw new IllegalArgumentException("Negative size");
                int[] totients = new int[n + 1];
                for (int i = 0; i <= n; i++)
                        totients[i] = i;
                
                for (int i = 2; i <= n; i++) {
                        if (totients[i] == i) { // i is prime
                                for (int j = i; j <= n; j += i)
                                        totients[j] = totients[j] / i * (i - 1);
                        }
                }
                return totients;
        }
        
        
        // Returns the same result as x.multiply(y), but is faster for large integers.
        public static BigInteger multiply(BigInteger x, BigInteger y) {
                final int CUTOFF = 1536;
                if (x.bitLength() <= CUTOFF || y.bitLength() <= CUTOFF) { // Base case
                        return x.multiply(y);
                        
                } else { // Karatsuba fast multiplication
                        int n = Math.max(x.bitLength(), y.bitLength());
                        int half = (n + 32) / 64 * 32;
                        BigInteger mask = BigInteger.ONE.shiftLeft(half).subtract(BigInteger.ONE);
                        BigInteger xlow = x.and(mask);
                        BigInteger ylow = y.and(mask);
                        BigInteger xhigh = x.shiftRight(half);
                        BigInteger yhigh = y.shiftRight(half);
                        
                        BigInteger a = multiply(xhigh, yhigh);
                        BigInteger b = multiply(xlow.add(xhigh), ylow.add(yhigh));
                        BigInteger c = multiply(xlow, ylow);
                        BigInteger d = b.subtract(a).subtract(c);
                        return a.shiftLeft(half).add(d).shiftLeft(half).add(c);
                }
        }
        
        
        // Advances the given sequence to the next permutation and returns whether a permutation was performed.
        // If no permutation was performed, then the input state was already the last possible permutation (a non-ascending sequence).
        // For example:
        // - nextPermutation({0,0,1}) changes the argument array to {0,1,0} and returns true.
        // - nextPermutation({1,0,0}) leaves the argument array unchanged and returns false.
        public static boolean nextPermutation(int[] a) {
                int i, n = a.length;
                for (i = n - 2; ; i--) {
                        if (i < 0)
                                return false;
                        if (a[i] < a[i + 1])
                                break;
                }
                for (int j = 1; i + j < n - j; j++) {
                        int tp = a[i + j];
                        a[i + j] = a[n - j];
                        a[n - j] = tp;
                }
                int j;
                for (j = i + 1; a[j] <= a[i]; j++);
                int tp = a[i];
                a[i] = a[j];
                a[j] = tp;
                return true;
        }
        
}
// Immutable unlimited precision fraction
final class Fraction {
        
        public final BigInteger numerator; // Always coprime with denominator
        public final BigInteger denominator; // Always positive
        
        
        public Fraction(BigInteger numer, BigInteger denom) {
                if (denom.signum() == 0)
                        throw new ArithmeticException("Division by zero");
                
                // Reduce to canonical form
                if (denom.signum() == -1) {
                        numer = numer.negate();
                        denom = denom.negate();
                }
                BigInteger gcd = numer.gcd(denom);
                if (!gcd.equals(BigInteger.ONE)) {
                        numer = numer.divide(gcd);
                        denom = denom.divide(gcd);
                }
                
                numerator = numer;
                denominator = denom;
        }
        
        
        public Fraction add(Fraction other) {
                return new Fraction(numerator.multiply(other.denominator).add(other.numerator.multiply(denominator)), denominator.multiply(other.denominator));
        }
        
        
        public Fraction subtract(Fraction other) {
                return new Fraction(numerator.multiply(other.denominator).subtract(other.numerator.multiply(denominator)), denominator.multiply(other.denominator));
        }
        
        
        public Fraction multiply(Fraction other) {
                return new Fraction(numerator.multiply(other.numerator), denominator.multiply(other.denominator));
        }
        
        
        public Fraction divide(Fraction other) {
                return new Fraction(numerator.multiply(other.denominator), denominator.multiply(other.numerator));
        }
        
        
        public boolean equals(Object obj) {
                if (obj instanceof Fraction) {
                        Fraction other = (Fraction)obj;
                        return numerator.equals(other.numerator) && denominator.equals(other.denominator);
                } else
                        return false;
        }
        
        
        public int hashCode() {
                return numerator.hashCode() + denominator.hashCode();
        }
        
        
        public String toString() {
                return numerator + "/" + denominator;
        }
        
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact