The sides of a triangle is constrained by the rule that the sum of any of its two sides is always bigger than the third side. Using this rule, we can find whether 3 sides given for a triangle is valid or not. The following sample Java program checks whether the given 3 sides can form a valid triangle.
import java.util.Scanner;
/**
* Validates whether the given 3 sides can form a triangle or not.
* @author jj
*/
public class ValidTriangle {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.println("Enter length of first side of triangle:");
double a = sn.nextDouble();
System.out.println("Enter length of second side of triangle:");
double b = sn.nextDouble();
System.out.println("Enter length of third side of triangle:");
double c = sn.nextDouble();
ValidTriangle vt = new ValidTriangle();
if(vt.isTriangleValid(a, b, c)) {
System.out.println("Sides entered can form a triangle!");
}else {
System.out.println("Sides entered cannot form a triangle!");
}
}
/**
* Checks whether the 3 sides can form a triangle
* The sum of any two sides must be greater than the other side
* @param a
* @param b
* @param c
* @return
*/
private boolean isTriangleValid(double a, double b, double c) {
if((a+b)>c && (a+c)>b && (b+c)>a) {
return true;
}else {
return false;
}
}
}
Posted in Java | Comments Off on How to Check If a Triangle Can be Formed in Java
Area of any type of triangle can be calculated using the formula, Area = (b*h)/2, where b is the base of the triangle and h is the vertical height. The following diagram shows how to define base and vertical height of a triangle.
The following sample Java program calculates the area of a triangle given its base and vertical height. Note that this approach works for any triangle.
import java.util.Scanner;
/**
* Calculates area of triangle in Java given its base and vertical height.
* @author jj
*/
public class AreaOfTriangle1 {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.println("Enter base of triangle:");
double base = sn.nextDouble();
System.out.println("Enter vertical height of triangle:");
double verticalHeight = sn.nextDouble();
AreaOfTriangle1 at = new AreaOfTriangle1();
double area = at.calculateArea(base,verticalHeight);
System.out.println("Area = "+area);
}
/**
* Calculates area of a triangle using base and vertical height
* @param base
* @param verticalHeight
* @return
*/
private double calculateArea(double base, double verticalHeight) {
return base*verticalHeight/2;
}
}
However if you don't know base and vertical height, you can also calculate area of a triangle using Heron's formula. This requires the length of all three sides of the triangle. According to heron's formula, the area of a triangle with 3 sides a, b and c is,
Area = square root of (p*(p-a)*(p-b)*(p-c)) (where p = (a+b+c)/2).
The following sample Java program calculates the area of a triangle given the length of its 3 sides. The following Java program also checks whether the given 3 sides can form part of a triangle. For a triangle, the sum of its 2 sides will always be greater than the third side.
import java.util.Scanner;
/**
* Calculates area of triangle in Java given its 3 sides.
* @author jj
*/
public class AreaOfTriangle2 {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.println("Enter length of first side of triangle:");
double a = sn.nextDouble();
System.out.println("Enter length of second side of triangle:");
double b = sn.nextDouble();
System.out.println("Enter length of third side of triangle:");
double c = sn.nextDouble();
AreaOfTriangle2 at = new AreaOfTriangle2();
if(at.isTriangleValid(a, b, c)) {
double area = at.calculateArea(a,b,c);
System.out.println("Area = "+area);
}else {
System.out.println("Sides entered cannot form a triangle!");
}
}
/**
* Calculates area of a triangle using length of its 3 sides
*/
private double calculateArea(double a, double b, double c) {
double p = (a+b+c)/2;
return Math.sqrt(p*(p-a)*(p-b)*(p-c));
}
/**
* Checks whether the 3 sides can form a triangle
* The sum of any two sides must be greater than the other side
* @param a
* @param b
* @param c
* @return
*/
private boolean isTriangleValid(double a, double b, double c) {
if((a+b)>c && (a+c)>b && (b+c)>a) {
return true;
}else {
return false;
}
}
}
Posted in Java | Comments Off on How to Calculate Area of Triangle in Java
Linear search is one of the simplest algorithms for searching data. In linear search, the entire data set is searched in a linear fashion for an input data. It is a kind of brute-force search and in the worst case scenario, the entire data set will have to be searched. Hence worst case cost is proportional to the number of elements in data set. The good thing about linear search is that the data set need not be ordered.
The following sample Java program demonstrates how linear search is performed to search a specific color in a list of colors. We sequentially take each color from the color list and compare with the color entered by the user. On finding the color, we immediately stop the iteration and print the results.
import java.util.Scanner;
/**
* Example program in Java demonstrating linear search
* @author
*/
public class LinearSearchExample {
private static final String[] COLOR_LIST = new String[] {
"blue","red","green","yellow", "blue","white","black","orange","pink"
};
public static void main(String[] args) {
System.out.println("Please enter a color to search for:");
Scanner sn = new Scanner(System.in);
String colorToSearch = sn.nextLine();
LinearSearchExample ls = new LinearSearchExample();
int position = ls.findColor(colorToSearch);
if(position <0) {
System.out.println("Sorry, the color is not found in the list");
}else {
System.out.println("Found color "+colorToSearch+" at position "+position);
}
}
/**
* Demonstrates linear search in Java
* Using linear search, looks up the color in a fixed list of colors
* If color is found, the position is returned, else returns -1
* Since linear search goes through entire list of elements in the worst case,
* its cost is proportional to number of elements
* @param colorToSearch
* @return
*/
private int findColor(String colorToSearch) {
int foundAt = -1;
for(int i=0;i<COLOR_LIST.length;i++) {
if(COLOR_LIST[i].equalsIgnoreCase(colorToSearch)) {
foundAt = i;
break;// found the color! no need to loop further!
}
}
return foundAt;
}
}
Posted in Java | Comments Off on How to do Linear Search in Java
Fisher-Yates shuffle or Knuth shuffle is an algorithm for generating a random shuffle of a finite set. A typical use case would be shuffling the characters in a word or string. A modern efficient variant of Fisher-Yates is known as Durstenfeld algorithm.
The Durstenfeld algorithm is,
for i from 0 to n − 2 do
j is a random integer such that i <= j < n
exchange a[j] and a[i]
end for
The following Java program demonstrates the use of Durstenfeld algorithm for shuffling characters in a word.
import java.util.concurrent.ThreadLocalRandom;
/**
* Example Java program to shuffle a word randomly using
* modified Fisher-Yates algorithm (Durstenfeld algorithm)
*/
public class ShuffleWord2 {
public static void main(String[] args) {
ShuffleWord2 sw = new ShuffleWord2();
String word = "Superman";
String shuffled = sw.shuffle(word);
System.out.println("Original word:"+word);
System.out.println("Shuffled word:"+shuffled);
}
/**
* Shuffles a given word. Uses Fisher-Yates/Durstenfeld algorithm
* @param word
* @return
*/
private String shuffle(String word) {
String shuffledWord = word; // start with original
int wordSize = word.length();
for(int i=0;i<wordSize-1;i++) {
int j = ThreadLocalRandom.current().nextInt(i, wordSize);
shuffledWord = swapCharacters(shuffledWord,j,i);
}
return shuffledWord;
}
/**
* Swaps characters in a string using the given character positions
* @param shuffledWord
* @param position1
* @param position2
* @return
*/
private String swapCharacters(String shuffledWord, int position1, int position2) {
char[] charArray = shuffledWord.toCharArray();
// Replace with a "swap" function, if desired:
char temp = charArray[position1];
charArray[position1] = charArray[position2];
charArray[position2] = temp;
return new String(charArray);
}
}
Posted in Java | Comments Off on Fisher Yates or Durstenfeld Shuffle in Java
Shuffling characters in a word involves randomly swapping letters in the word. It is used in vocabulary games such as Jumble game to improve English language skills.
The following Java program shuffles a given word. The shuffling is achieved by randomly swapping characters 10 times (just an arbitrary number). It can be improved by replacing the shuffle count 10 by another random number. Note that this algorithm is not the best algorithm for shuffling. A better approach will be swapping every character in the word by another random character in the word or using well known shuffling algorithms such as Fisher-Yates algorithm or Durstenfeld algorithm.
import java.util.concurrent.ThreadLocalRandom;
/**
* Java program to shuffle a word randomly
*/
public class ShuffleWord {
public static void main(String[] args) {
ShuffleWord sw = new ShuffleWord();
String word = "Hello";
String shuffled = sw.shuffle(word);
System.out.println("Original word:"+word);
System.out.println("Shuffled word:"+shuffled);
}
/**
* Shuffles a given word. Randomly swaps characters 10 times.
* @param word
* @return
*/
private String shuffle(String word) {
String shuffledWord = word; // start with original
int wordSize = word.length();
int shuffleCount = 10; // let us randomly shuffle letters 10 times
for(int i=0;i<shuffleCount;i++) {
//swap letters in two indexes
int position1 = ThreadLocalRandom.current().nextInt(0, wordSize);
int position2 = ThreadLocalRandom.current().nextInt(0, wordSize);
shuffledWord = swapCharacters(shuffledWord,position1,position2);
}
return shuffledWord;
}
/**
* Swaps characters in a string using the given character positions
* @param shuffledWord
* @param position1
* @param position2
* @return
*/
private String swapCharacters(String shuffledWord, int position1, int position2) {
char[] charArray = shuffledWord.toCharArray();
// Replace with a "swap" function, if desired:
char temp = charArray[position1];
charArray[position1] = charArray[position2];
charArray[position2] = temp;
return new String(charArray);
}
}
Posted in Java | Comments Off on How to Shuffle a Word in Java