mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
Change project structure to a Maven Java project + Refactor (#2816)
This commit is contained in:
committed by
GitHub
parent
8e533d2617
commit
9fb3364ccc
108
src/main/java/com/thealgorithms/misc/ColorContrastRatio.java
Normal file
108
src/main/java/com/thealgorithms/misc/ColorContrastRatio.java
Normal file
@@ -0,0 +1,108 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
/**
|
||||
* @brief A Java implementation of the offcial W3 documented procedure to
|
||||
* calculate contrast ratio between colors on the web. This is used to calculate
|
||||
* the readability of a foreground color on top of a background color.
|
||||
* @since 2020-10-15
|
||||
* @see [Color Contrast
|
||||
* Ratio](https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-procedure)
|
||||
* @author [Seth Falco](https://github.com/SethFalco)
|
||||
*/
|
||||
public class ColorContrastRatio {
|
||||
|
||||
/**
|
||||
* @brief Calculates the contrast ratio between two given colors.
|
||||
* @param a Any color, used to get the red, green, and blue values.
|
||||
* @param b Another color, which will be compared against the first color.
|
||||
* @return The contrast ratio between the two colors.
|
||||
*/
|
||||
public double getContrastRatio(Color a, Color b) {
|
||||
final double aColorLuminance = getRelativeLuminance(a);
|
||||
final double bColorLuminance = getRelativeLuminance(b);
|
||||
|
||||
if (aColorLuminance > bColorLuminance) {
|
||||
return (aColorLuminance + 0.05) / (bColorLuminance + 0.05);
|
||||
}
|
||||
|
||||
return (bColorLuminance + 0.05) / (aColorLuminance + 0.05);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculates the relative luminance of a given color.
|
||||
* @param color Any color, used to get the red, green, and blue values.
|
||||
* @return The relative luminance of the color.
|
||||
* @see [More info on relative
|
||||
* luminance.](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef)
|
||||
*/
|
||||
public double getRelativeLuminance(Color color) {
|
||||
final double red = getColor(color.getRed());
|
||||
final double green = getColor(color.getGreen());
|
||||
final double blue = getColor(color.getBlue());
|
||||
|
||||
return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculates the final value for a color to be used in the relative
|
||||
* luminance formula as described in step 1.
|
||||
* @param color8Bit 8-bit representation of a color component value.
|
||||
* @return Value for the provided color component to be used in the relative
|
||||
* luminance formula.
|
||||
*/
|
||||
public double getColor(int color8Bit) {
|
||||
final double sRgb = getColorSRgb(color8Bit);
|
||||
return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculates the Color sRGB value as denoted in step 1 of the
|
||||
* procedure document.
|
||||
* @param color8Bit 8-bit representation of a color component value.
|
||||
* @return A percentile value of the color component.
|
||||
*/
|
||||
private double getColorSRgb(double color8Bit) {
|
||||
return color8Bit / 255.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* You can check this example against another open-source implementation
|
||||
* available on GitHub.
|
||||
*
|
||||
* @see [Online Contrast
|
||||
* Ratio](https://contrast-ratio.com/#rgb%28226%2C%20229%2C%20248-on-rgb%2823%2C%20103%2C%20154%29)
|
||||
* @see [GitHub Repository for Online Contrast
|
||||
* Ratio](https://github.com/LeaVerou/contrast-ratio)
|
||||
*/
|
||||
private static void test() {
|
||||
final ColorContrastRatio algImpl = new ColorContrastRatio();
|
||||
|
||||
final Color black = Color.BLACK;
|
||||
final double blackLuminance = algImpl.getRelativeLuminance(black);
|
||||
assert blackLuminance == 0 : "Test 1 Failed - Incorrect relative luminance.";
|
||||
|
||||
final Color white = Color.WHITE;
|
||||
final double whiteLuminance = algImpl.getRelativeLuminance(white);
|
||||
assert whiteLuminance == 1 : "Test 2 Failed - Incorrect relative luminance.";
|
||||
|
||||
final double highestColorRatio = algImpl.getContrastRatio(black, white);
|
||||
assert highestColorRatio == 21 : "Test 3 Failed - Incorrect contrast ratio.";
|
||||
|
||||
final Color foreground = new Color(23, 103, 154);
|
||||
final double foregroundLuminance = algImpl.getRelativeLuminance(foreground);
|
||||
assert foregroundLuminance == 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance.";
|
||||
|
||||
final Color background = new Color(226, 229, 248);
|
||||
final double backgroundLuminance = algImpl.getRelativeLuminance(background);
|
||||
assert backgroundLuminance == 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance.";
|
||||
|
||||
final double contrastRatio = algImpl.getContrastRatio(foreground, background);
|
||||
assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio.";
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
test();
|
||||
}
|
||||
}
|
||||
127
src/main/java/com/thealgorithms/misc/InverseOfMatrix.java
Normal file
127
src/main/java/com/thealgorithms/misc/InverseOfMatrix.java
Normal file
@@ -0,0 +1,127 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/*
|
||||
* Wikipedia link : https://en.wikipedia.org/wiki/Invertible_matrix
|
||||
*
|
||||
* Here we use gauss elimination method to find the inverse of a given matrix.
|
||||
* To understand gauss elimination method to find inverse of a matrix: https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination
|
||||
*
|
||||
* We can also find the inverse of a matrix
|
||||
*/
|
||||
public class InverseOfMatrix {
|
||||
|
||||
public static void main(String argv[]) {
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.println("Enter the matrix size (Square matrix only): ");
|
||||
int n = input.nextInt();
|
||||
double a[][] = new double[n][n];
|
||||
System.out.println("Enter the elements of matrix: ");
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
a[i][j] = input.nextDouble();
|
||||
}
|
||||
}
|
||||
|
||||
double d[][] = invert(a);
|
||||
System.out.println();
|
||||
System.out.println("The inverse is: ");
|
||||
for (int i = 0; i < n; ++i) {
|
||||
for (int j = 0; j < n; ++j) {
|
||||
System.out.print(d[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
input.close();
|
||||
}
|
||||
|
||||
public static double[][] invert(double a[][]) {
|
||||
int n = a.length;
|
||||
double x[][] = new double[n][n];
|
||||
double b[][] = new double[n][n];
|
||||
int index[] = new int[n];
|
||||
for (int i = 0; i < n; ++i) {
|
||||
b[i][i] = 1;
|
||||
}
|
||||
|
||||
// Transform the matrix into an upper triangle
|
||||
gaussian(a, index);
|
||||
|
||||
// Update the matrix b[i][j] with the ratios stored
|
||||
for (int i = 0; i < n - 1; ++i) {
|
||||
for (int j = i + 1; j < n; ++j) {
|
||||
for (int k = 0; k < n; ++k) {
|
||||
b[index[j]][k]
|
||||
-= a[index[j]][i] * b[index[i]][k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Perform backward substitutions
|
||||
for (int i = 0; i < n; ++i) {
|
||||
x[n - 1][i] = b[index[n - 1]][i] / a[index[n - 1]][n - 1];
|
||||
for (int j = n - 2; j >= 0; --j) {
|
||||
x[j][i] = b[index[j]][i];
|
||||
for (int k = j + 1; k < n; ++k) {
|
||||
x[j][i] -= a[index[j]][k] * x[k][i];
|
||||
}
|
||||
x[j][i] /= a[index[j]][j];
|
||||
}
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
// Method to carry out the partial-pivoting Gaussian
|
||||
// elimination. Here index[] stores pivoting order.
|
||||
public static void gaussian(double a[][], int index[]) {
|
||||
int n = index.length;
|
||||
double c[] = new double[n];
|
||||
|
||||
// Initialize the index
|
||||
for (int i = 0; i < n; ++i) {
|
||||
index[i] = i;
|
||||
}
|
||||
|
||||
// Find the rescaling factors, one from each row
|
||||
for (int i = 0; i < n; ++i) {
|
||||
double c1 = 0;
|
||||
for (int j = 0; j < n; ++j) {
|
||||
double c0 = Math.abs(a[i][j]);
|
||||
if (c0 > c1) {
|
||||
c1 = c0;
|
||||
}
|
||||
}
|
||||
c[i] = c1;
|
||||
}
|
||||
|
||||
// Search the pivoting element from each column
|
||||
int k = 0;
|
||||
for (int j = 0; j < n - 1; ++j) {
|
||||
double pi1 = 0;
|
||||
for (int i = j; i < n; ++i) {
|
||||
double pi0 = Math.abs(a[index[i]][j]);
|
||||
pi0 /= c[index[i]];
|
||||
if (pi0 > pi1) {
|
||||
pi1 = pi0;
|
||||
k = i;
|
||||
}
|
||||
}
|
||||
// Interchange rows according to the pivoting order
|
||||
int itmp = index[j];
|
||||
index[j] = index[k];
|
||||
index[k] = itmp;
|
||||
for (int i = j + 1; i < n; ++i) {
|
||||
double pj = a[index[i]][j] / a[index[j]][j];
|
||||
|
||||
// Record pivoting ratios below the diagonal
|
||||
a[index[i]][j] = pj;
|
||||
|
||||
// Modify other elements accordingly
|
||||
for (int l = j + 1; l < n; ++l) {
|
||||
a[index[i]][l] -= pj * a[index[j]][l];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
/**
|
||||
* @author shrutisheoran
|
||||
*/
|
||||
public class MedianOfRunningArray {
|
||||
|
||||
private PriorityQueue<Integer> p1;
|
||||
private PriorityQueue<Integer> p2;
|
||||
|
||||
// Constructor
|
||||
public MedianOfRunningArray() {
|
||||
this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap
|
||||
this.p2 = new PriorityQueue<>(); // Min Heap
|
||||
}
|
||||
|
||||
/*
|
||||
Inserting lower half of array to max Heap
|
||||
and upper half to min heap
|
||||
*/
|
||||
public void insert(Integer e) {
|
||||
p2.add(e);
|
||||
if (p2.size() - p1.size() > 1) {
|
||||
p1.add(p2.remove());
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Returns median at any given point
|
||||
*/
|
||||
public Integer median() {
|
||||
if (p1.size() == p2.size()) {
|
||||
return (p1.peek() + p2.peek()) / 2;
|
||||
}
|
||||
return p1.size() > p2.size() ? p1.peek() : p2.peek();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
/*
|
||||
Testing the median function
|
||||
*/
|
||||
|
||||
MedianOfRunningArray p = new MedianOfRunningArray();
|
||||
int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
|
||||
for (int i = 0; i < 9; i++) {
|
||||
p.insert(arr[i]);
|
||||
System.out.print(p.median() + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
49
src/main/java/com/thealgorithms/misc/PalindromePrime.java
Normal file
49
src/main/java/com/thealgorithms/misc/PalindromePrime.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class PalindromePrime {
|
||||
|
||||
public static void main(String[] args) { // Main funtion
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Enter the quantity of First Palindromic Primes you want");
|
||||
int n = in.nextInt(); // Input of how many first palindromic prime we want
|
||||
functioning(n); // calling function - functioning
|
||||
in.close();
|
||||
}
|
||||
|
||||
public static boolean prime(int num) { // checking if number is prime or not
|
||||
for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) {
|
||||
if (num % divisor == 0) {
|
||||
return false; // false if not prime
|
||||
}
|
||||
}
|
||||
return true; // True if prime
|
||||
}
|
||||
|
||||
public static int reverse(int n) { // Returns the reverse of the number
|
||||
int reverse = 0;
|
||||
while (n != 0) {
|
||||
reverse *= 10;
|
||||
reverse += n % 10;
|
||||
n /= 10;
|
||||
}
|
||||
return reverse;
|
||||
}
|
||||
|
||||
public static void functioning(int y) {
|
||||
if (y == 0) {
|
||||
return;
|
||||
}
|
||||
System.out.print(2 + "\n"); // print the first Palindromic Prime
|
||||
int count = 1;
|
||||
int num = 3;
|
||||
while (count < y) {
|
||||
if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
|
||||
count++; // counts check when to terminate while loop
|
||||
System.out.print(num + "\n"); // print the Palindromic Prime
|
||||
}
|
||||
num += 2; // inrease iterator value by two
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.Stack;
|
||||
import com.thealgorithms.datastructures.lists.SinglyLinkedList;
|
||||
|
||||
/**
|
||||
* A simple way of knowing if a singly linked list is palindrome is to push all
|
||||
* the values into a Stack and then compare the list to popped vales from the
|
||||
* Stack.
|
||||
*
|
||||
* See more:
|
||||
* https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
|
||||
*/
|
||||
public class PalindromeSinglyLinkedList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SinglyLinkedList linkedList = new SinglyLinkedList();
|
||||
|
||||
linkedList.insertHead(3);
|
||||
linkedList.insertNth(2, 1);
|
||||
linkedList.insertNth(1, 2);
|
||||
linkedList.insertNth(2, 3);
|
||||
linkedList.insertNth(3, 4);
|
||||
|
||||
if (isPalindrome(linkedList)) {
|
||||
System.out.println("It's a palindrome list");
|
||||
} else {
|
||||
System.out.println("It's NOT a palindrome list");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isPalindrome(SinglyLinkedList linkedList) {
|
||||
boolean ret = true;
|
||||
Stack<Integer> linkedListValues = new Stack<>();
|
||||
|
||||
for (int i = 0; i < linkedList.size(); i++) {
|
||||
linkedListValues.push(linkedList.getNth(i));
|
||||
}
|
||||
|
||||
for (int i = 0; i < linkedList.size(); i++) {
|
||||
if (linkedList.getNth(i) != linkedListValues.pop()) {
|
||||
ret = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
99
src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
Normal file
99
src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
Normal file
@@ -0,0 +1,99 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class RangeInSortedArray {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Testcases
|
||||
assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 3), new int[]{2, 4});
|
||||
assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 4), new int[]{5, 5});
|
||||
assert Arrays.equals(sortedRange(new int[]{0, 1, 2}, 3), new int[]{-1, -1});
|
||||
}
|
||||
|
||||
// Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums'
|
||||
// Gives [-1, -1] in case element doesn't exist in array
|
||||
public static int[] sortedRange(int[] nums, int key) {
|
||||
int[] range = new int[]{-1, -1};
|
||||
alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true);
|
||||
alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false);
|
||||
return range;
|
||||
}
|
||||
|
||||
// Recursive altered binary search which searches for leftmost as well as rightmost occurrence of
|
||||
// 'key'
|
||||
public static void alteredBinSearch(
|
||||
int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
|
||||
if (left > right) {
|
||||
return;
|
||||
}
|
||||
int mid = (left + right) / 2;
|
||||
if (nums[mid] > key) {
|
||||
alteredBinSearch(nums, key, left, mid - 1, range, goLeft);
|
||||
} else if (nums[mid] < key) {
|
||||
alteredBinSearch(nums, key, mid + 1, right, range, goLeft);
|
||||
} else {
|
||||
if (goLeft) {
|
||||
if (mid == 0 || nums[mid - 1] != key) {
|
||||
range[0] = mid;
|
||||
} else {
|
||||
alteredBinSearch(nums, key, left, mid - 1, range, goLeft);
|
||||
}
|
||||
} else {
|
||||
if (mid == nums.length - 1 || nums[mid + 1] != key) {
|
||||
range[1] = mid;
|
||||
} else {
|
||||
alteredBinSearch(nums, key, mid + 1, right, range, goLeft);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Iterative altered binary search which searches for leftmost as well as rightmost occurrence of
|
||||
// 'key'
|
||||
public static void alteredBinSearchIter(
|
||||
int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
|
||||
while (left <= right) {
|
||||
int mid = (left + right) / 2;
|
||||
if (nums[mid] > key) {
|
||||
right = mid - 1;
|
||||
} else if (nums[mid] < key) {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
if (goLeft) {
|
||||
if (mid == 0 || nums[mid - 1] != key) {
|
||||
range[0] = mid;
|
||||
return;
|
||||
} else {
|
||||
right = mid - 1;
|
||||
}
|
||||
} else {
|
||||
if (mid == nums.length - 1 || nums[mid + 1] != key) {
|
||||
range[1] = mid;
|
||||
return;
|
||||
} else {
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int getCountLessThan(int[] nums, int key) {
|
||||
return getLessThan(nums, key, 0, nums.length - 1);
|
||||
}
|
||||
|
||||
public static int getLessThan(int[] nums, int key, int left, int right) {
|
||||
int count = 0;
|
||||
while (left <= right) {
|
||||
int mid = (left + right) / 2;
|
||||
if (nums[mid] > key) {
|
||||
right = mid - 1;
|
||||
} else if (nums[mid] <= key) {
|
||||
count = mid + 1; // Atleast mid+1 elements exist which are <= key
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
58
src/main/java/com/thealgorithms/misc/Sort012D.java
Normal file
58
src/main/java/com/thealgorithms/misc/Sort012D.java
Normal file
@@ -0,0 +1,58 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* The array is divided into four sections: a[1..Lo-1] zeroes a[Lo..Mid-1] ones
|
||||
* a[Mid..Hi] unknown a[Hi+1..N] twos If array [mid] =0, then swap array [mid]
|
||||
* with array [low] and increment both pointers once. If array [mid] = 1, then
|
||||
* no swapping is required. Increment mid pointer once. If array [mid] = 2, then
|
||||
* we swap array [mid] with array [high] and decrement the high pointer once.
|
||||
* For more information on the Dutch national flag algorithm refer
|
||||
* https://en.wikipedia.org/wiki/Dutch_national_flag_problem
|
||||
*/
|
||||
public class Sort012D {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Scanner np = new Scanner(System.in);
|
||||
int n = np.nextInt();
|
||||
int a[] = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
a[i] = np.nextInt();
|
||||
}
|
||||
sort012(a);
|
||||
}
|
||||
|
||||
public static void sort012(int[] a) {
|
||||
int l = 0;
|
||||
int h = a.length - 1;
|
||||
int mid = 0;
|
||||
int temp;
|
||||
while (mid <= h) {
|
||||
switch (a[mid]) {
|
||||
case 0: {
|
||||
temp = a[l];
|
||||
a[l] = a[mid];
|
||||
a[mid] = temp;
|
||||
l++;
|
||||
mid++;
|
||||
break;
|
||||
}
|
||||
case 1:
|
||||
mid++;
|
||||
break;
|
||||
case 2: {
|
||||
temp = a[mid];
|
||||
a[mid] = a[h];
|
||||
a[h] = temp;
|
||||
h--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("the Sorted array is ");
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
System.out.print(+a[i] + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
51
src/main/java/com/thealgorithms/misc/Sparcity.java
Normal file
51
src/main/java/com/thealgorithms/misc/Sparcity.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/*
|
||||
*A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse).
|
||||
*The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse.
|
||||
*
|
||||
* @author Ojasva Jain
|
||||
*/
|
||||
|
||||
class Sparcity {
|
||||
|
||||
/*
|
||||
* @return Sparcity of matrix
|
||||
*
|
||||
* where sparcity = number of zeroes/total elements in matrix
|
||||
*
|
||||
*/
|
||||
static double sparcity(double[][] mat) {
|
||||
int zero = 0;
|
||||
//Traversing the matrix to count number of zeroes
|
||||
for (int i = 0; i < mat.length; i++) {
|
||||
for (int j = 0; j < mat[i].length; j++) {
|
||||
if (mat[i][j] == 0) {
|
||||
zero++;
|
||||
}
|
||||
}
|
||||
}
|
||||
//return sparcity
|
||||
return ((double) zero / (mat.length * mat[1].length));
|
||||
}
|
||||
|
||||
//Driver method
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Enter number of rows in matrix: ");
|
||||
int n = in.nextInt();
|
||||
System.out.println("Enter number of Columns in matrix: ");
|
||||
int m = in.nextInt();
|
||||
|
||||
System.out.println("Enter Matrix elements: ");
|
||||
double[][] mat = new double[n][m];
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < m; j++) {
|
||||
mat[i][j] = in.nextDouble();
|
||||
}
|
||||
}
|
||||
System.out.println("Sparcity of matrix is: " + sparcity(mat));
|
||||
}
|
||||
}
|
||||
102
src/main/java/com/thealgorithms/misc/ThreeSumProblem.java
Normal file
102
src/main/java/com/thealgorithms/misc/ThreeSumProblem.java
Normal file
@@ -0,0 +1,102 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ThreeSumProblem {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.print("Enter the target sum ");
|
||||
int ts = scan.nextInt();
|
||||
System.out.print("Enter the number of elements in the array ");
|
||||
int n = scan.nextInt();
|
||||
System.out.println("Enter all your array elements:");
|
||||
int arr[] = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
arr[i] = scan.nextInt();
|
||||
}
|
||||
ThreeSumProblem th = new ThreeSumProblem();
|
||||
System.out.println("Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n");
|
||||
System.out.println("Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n");
|
||||
System.out.println("Hashmap Approach\n" + (th.Hashmap(arr, ts)));
|
||||
|
||||
}
|
||||
|
||||
public List<List<Integer>> BruteForce(int[] nums, int target) {
|
||||
List<List<Integer>> arr = new ArrayList<List<Integer>>();
|
||||
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
for (int j = i + 1; j < nums.length; j++) {
|
||||
for (int k = j + 1; k < nums.length; k++) {
|
||||
if (nums[i] + nums[j] + nums[k] == target) {
|
||||
List<Integer> temp = new ArrayList<>();
|
||||
temp.add(nums[i]);
|
||||
temp.add(nums[j]);
|
||||
temp.add(nums[k]);
|
||||
Collections.sort(temp);
|
||||
arr.add(temp);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
arr = new ArrayList<List<Integer>>(new LinkedHashSet<List<Integer>>(arr));
|
||||
return arr;
|
||||
}
|
||||
|
||||
public List<List<Integer>> TwoPointer(int[] nums, int target) {
|
||||
Arrays.sort(nums);
|
||||
List<List<Integer>> arr = new ArrayList<List<Integer>>();
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
int i = 0;
|
||||
while (i < nums.length - 1) {
|
||||
start = i + 1;
|
||||
end = nums.length - 1;
|
||||
while (start < end) {
|
||||
if (nums[start] + nums[end] + nums[i] == target) {
|
||||
List<Integer> temp = new ArrayList<>();
|
||||
temp.add(nums[i]);
|
||||
temp.add(nums[start]);
|
||||
temp.add(nums[end]);
|
||||
arr.add(temp);
|
||||
start++;
|
||||
end--;
|
||||
} else if (nums[start] + nums[end] + nums[i] < target) {
|
||||
start += 1;
|
||||
} else {
|
||||
end -= 1;
|
||||
}
|
||||
|
||||
}
|
||||
i++;
|
||||
}
|
||||
Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(arr);
|
||||
return new ArrayList<List<Integer>>(set);
|
||||
}
|
||||
|
||||
public List<List<Integer>> Hashmap(int[] nums, int target) {
|
||||
Arrays.sort(nums);
|
||||
Set<List<Integer>> ts = new HashSet();
|
||||
HashMap<Integer, Integer> hm = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
hm.put(nums[i], i);
|
||||
}
|
||||
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
for (int j = i + 1; j < nums.length; j++) {
|
||||
int t = target - nums[i] - nums[j];
|
||||
if (hm.containsKey(t) && hm.get(t) > j) {
|
||||
List<Integer> temp = new ArrayList<>();
|
||||
temp.add(nums[i]);
|
||||
temp.add(nums[j]);
|
||||
temp.add(t);
|
||||
ts.add(temp);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ArrayList(ts);
|
||||
}
|
||||
|
||||
}
|
||||
101
src/main/java/com/thealgorithms/misc/TwoSumProblem.java
Normal file
101
src/main/java/com/thealgorithms/misc/TwoSumProblem.java
Normal file
@@ -0,0 +1,101 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TwoSumProblem {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.print("Enter the target sum ");
|
||||
int ts = scan.nextInt();
|
||||
System.out.print("Enter the number of elements in the array ");
|
||||
int n = scan.nextInt();
|
||||
System.out.println("Enter all your array elements:");
|
||||
int arr[] = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
arr[i] = scan.nextInt();
|
||||
}
|
||||
TwoSumProblem t = new TwoSumProblem();
|
||||
System.out.println("Brute Force Approach\n" + Arrays.toString(t.BruteForce(arr, ts)) + "\n");
|
||||
System.out.println("Two Pointer Approach\n" + Arrays.toString(t.TwoPointer(arr, ts)) + "\n");
|
||||
System.out.println("Hashmap Approach\n" + Arrays.toString(t.HashMap(arr, ts)));
|
||||
|
||||
}
|
||||
|
||||
public int[] BruteForce(int[] nums, int target) {
|
||||
//Brute Force Approach
|
||||
int ans[] = new int[2];
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
for (int j = i + 1; j < nums.length; j++) {
|
||||
if (nums[i] + nums[j] == target) {
|
||||
ans[0] = i;
|
||||
ans[1] = j;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
|
||||
public int[] TwoPointer(int[] nums, int target) {
|
||||
// HashMap Approach
|
||||
int ans[] = new int[2];
|
||||
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
hm.put(i, nums[i]);
|
||||
}
|
||||
HashMap<Integer, Integer> temp
|
||||
= hm.entrySet()
|
||||
.stream()
|
||||
.sorted((i1, i2)
|
||||
-> i1.getValue().compareTo(
|
||||
i2.getValue()))
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
Map.Entry::getValue,
|
||||
(e1, e2) -> e1, LinkedHashMap::new));
|
||||
|
||||
int start = 0;
|
||||
int end = nums.length - 1;
|
||||
while (start < end) {
|
||||
int currSum = (Integer) temp.values().toArray()[start] + (Integer) temp.values().toArray()[end];
|
||||
|
||||
if (currSum == target) {
|
||||
ans[0] = (Integer) temp.keySet().toArray()[start];
|
||||
ans[1] = (Integer) temp.keySet().toArray()[end];
|
||||
break;
|
||||
} else if (currSum > target) {
|
||||
end -= 1;
|
||||
} else if (currSum < target) {
|
||||
start += 1;
|
||||
}
|
||||
|
||||
}
|
||||
return ans;
|
||||
|
||||
}
|
||||
|
||||
public int[] HashMap(int[] nums, int target) {
|
||||
//Using Hashmaps
|
||||
int ans[] = new int[2];
|
||||
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
hm.put(nums[i], i);
|
||||
}
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
int t = target - nums[i];
|
||||
if (hm.containsKey(t) && hm.get(t) != i) {
|
||||
ans[0] = i;
|
||||
ans[1] = hm.get(t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
|
||||
}
|
||||
154
src/main/java/com/thealgorithms/misc/WordBoggle.java
Normal file
154
src/main/java/com/thealgorithms/misc/WordBoggle.java
Normal file
@@ -0,0 +1,154 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class WordBoggle {
|
||||
|
||||
/**
|
||||
* O(nm * 8^s + ws) time where n = width of boggle board, m = height of
|
||||
* boggle board, s = length of longest word in string array, w = length of
|
||||
* string array, 8 is due to 8 explorable neighbours O(nm + ws) space.
|
||||
*/
|
||||
public static List<String> boggleBoard(char[][] board, String[] words) {
|
||||
Trie trie = new Trie();
|
||||
for (String word : words) {
|
||||
trie.add(word);
|
||||
}
|
||||
Set<String> finalWords = new HashSet<>();
|
||||
boolean[][] visited = new boolean[board.length][board.length];
|
||||
for (int i = 0; i < board.length; i++) {
|
||||
for (int j = 0; j < board[i].length; j++) {
|
||||
explore(i, j, board, trie.root, visited, finalWords);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(finalWords);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Testcase
|
||||
List<String> ans
|
||||
= new ArrayList<>(
|
||||
Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
|
||||
assert (boggleBoard(
|
||||
new char[][]{
|
||||
{'t', 'h', 'i', 's', 'i', 's', 'a'},
|
||||
{'s', 'i', 'm', 'p', 'l', 'e', 'x'},
|
||||
{'b', 'x', 'x', 'x', 'x', 'e', 'b'},
|
||||
{'x', 'o', 'g', 'g', 'l', 'x', 'o'},
|
||||
{'x', 'x', 'x', 'D', 'T', 'r', 'a'},
|
||||
{'R', 'E', 'P', 'E', 'A', 'd', 'x'},
|
||||
{'x', 'x', 'x', 'x', 'x', 'x', 'x'},
|
||||
{'N', 'O', 'T', 'R', 'E', '_', 'P'},
|
||||
{'x', 'x', 'D', 'E', 'T', 'A', 'E'},},
|
||||
new String[]{
|
||||
"this",
|
||||
"is",
|
||||
"not",
|
||||
"a",
|
||||
"simple",
|
||||
"test",
|
||||
"boggle",
|
||||
"board",
|
||||
"REPEATED",
|
||||
"NOTRE_PEATED",})
|
||||
.equals(ans));
|
||||
}
|
||||
|
||||
public static void explore(
|
||||
int i,
|
||||
int j,
|
||||
char[][] board,
|
||||
TrieNode trieNode,
|
||||
boolean[][] visited,
|
||||
Set<String> finalWords) {
|
||||
if (visited[i][j]) {
|
||||
return;
|
||||
}
|
||||
|
||||
char letter = board[i][j];
|
||||
if (!trieNode.children.containsKey(letter)) {
|
||||
return;
|
||||
}
|
||||
visited[i][j] = true;
|
||||
trieNode = trieNode.children.get(letter);
|
||||
if (trieNode.children.containsKey('*')) {
|
||||
finalWords.add(trieNode.word);
|
||||
}
|
||||
|
||||
List<Integer[]> neighbors = getNeighbors(i, j, board);
|
||||
for (Integer[] neighbor : neighbors) {
|
||||
explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords);
|
||||
}
|
||||
|
||||
visited[i][j] = false;
|
||||
}
|
||||
|
||||
public static List<Integer[]> getNeighbors(int i, int j, char[][] board) {
|
||||
List<Integer[]> neighbors = new ArrayList<>();
|
||||
if (i > 0 && j > 0) {
|
||||
neighbors.add(new Integer[]{i - 1, j - 1});
|
||||
}
|
||||
|
||||
if (i > 0 && j < board[0].length - 1) {
|
||||
neighbors.add(new Integer[]{i - 1, j + 1});
|
||||
}
|
||||
|
||||
if (i < board.length - 1 && j < board[0].length - 1) {
|
||||
neighbors.add(new Integer[]{i + 1, j + 1});
|
||||
}
|
||||
|
||||
if (i < board.length - 1 && j > 0) {
|
||||
neighbors.add(new Integer[]{i + 1, j - 1});
|
||||
}
|
||||
|
||||
if (i > 0) {
|
||||
neighbors.add(new Integer[]{i - 1, j});
|
||||
}
|
||||
|
||||
if (i < board.length - 1) {
|
||||
neighbors.add(new Integer[]{i + 1, j});
|
||||
}
|
||||
|
||||
if (j > 0) {
|
||||
neighbors.add(new Integer[]{i, j - 1});
|
||||
}
|
||||
|
||||
if (j < board[0].length - 1) {
|
||||
neighbors.add(new Integer[]{i, j + 1});
|
||||
}
|
||||
|
||||
return neighbors;
|
||||
}
|
||||
}
|
||||
|
||||
// Trie used to optimize string search
|
||||
class TrieNode {
|
||||
|
||||
Map<Character, TrieNode> children = new HashMap<>();
|
||||
String word = "";
|
||||
}
|
||||
|
||||
class Trie {
|
||||
|
||||
TrieNode root;
|
||||
char endSymbol;
|
||||
|
||||
public Trie() {
|
||||
this.root = new TrieNode();
|
||||
this.endSymbol = '*';
|
||||
}
|
||||
|
||||
public void add(String str) {
|
||||
TrieNode node = this.root;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char letter = str.charAt(i);
|
||||
if (!node.children.containsKey(letter)) {
|
||||
TrieNode newNode = new TrieNode();
|
||||
node.children.put(letter, newNode);
|
||||
}
|
||||
node = node.children.get(letter);
|
||||
}
|
||||
node.children.put(this.endSymbol, null);
|
||||
node.word = str;
|
||||
}
|
||||
}
|
||||
78
src/main/java/com/thealgorithms/misc/matrixTranspose.java
Normal file
78
src/main/java/com/thealgorithms/misc/matrixTranspose.java
Normal file
@@ -0,0 +1,78 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* <h1>Find the Transpose of Matrix!</h1>
|
||||
*
|
||||
* Simply take input from the user and print the matrix before the transpose and
|
||||
* after the transpose.
|
||||
*
|
||||
* <p>
|
||||
* <b>Note:</b> Giving proper comments in your program makes it more user
|
||||
* friendly and it is assumed as a high quality code.
|
||||
*
|
||||
* @author Rajat-Jain29
|
||||
* @version 11.0.9
|
||||
* @since 2014-03-31
|
||||
*/
|
||||
public class matrixTranspose {
|
||||
|
||||
public static void main(String[] args) {
|
||||
/*
|
||||
* This is the main method
|
||||
*
|
||||
* @param args Unused.
|
||||
*
|
||||
* @return Nothing.
|
||||
*/
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int i, j, row, column;
|
||||
System.out.println("Enter the number of rows in the 2D matrix:");
|
||||
|
||||
/*
|
||||
* Take input from user for how many rows to be print
|
||||
*/
|
||||
row = sc.nextInt();
|
||||
|
||||
System.out.println("Enter the number of columns in the 2D matrix:");
|
||||
|
||||
/*
|
||||
* Take input from user for how many coloumn to be print
|
||||
*/
|
||||
column = sc.nextInt();
|
||||
int[][] arr = new int[row][column];
|
||||
System.out.println("Enter the elements");
|
||||
for (i = 0; i < row; i++) {
|
||||
for (j = 0; j < column; j++) {
|
||||
arr[i][j] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Print matrix before the Transpose in proper way
|
||||
*/
|
||||
System.out.println("The matrix is:");
|
||||
for (i = 0; i < row; i++) {
|
||||
for (j = 0; j < column; j++) {
|
||||
System.out.print(arr[i][j] + "\t");
|
||||
}
|
||||
System.out.print("\n");
|
||||
}
|
||||
|
||||
/*
|
||||
* Print matrix after the tranpose in proper way Transpose means Interchanging
|
||||
* of rows wth column so we interchange the rows in next loop Thus at last
|
||||
* matrix of transpose is obtained through user input...
|
||||
*/
|
||||
System.out.println("The Transpose of the given matrix is:");
|
||||
for (i = 0; i < column; i++) {
|
||||
for (j = 0; j < row; j++) {
|
||||
System.out.print(arr[j][i] + "\t");
|
||||
}
|
||||
System.out.print("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user