mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-26 05:59:22 +08:00
Format code with prettier (#3375)
This commit is contained in:
@ -4,30 +4,29 @@ package com.thealgorithms.others;
|
||||
* A left rotation operation on an array
|
||||
* shifts each of the array's elements
|
||||
* given integer n unit to the left.
|
||||
*
|
||||
* @author sangin-lee
|
||||
*
|
||||
* @author sangin-lee
|
||||
*/
|
||||
|
||||
public class ArrayLeftRotation {
|
||||
|
||||
/*
|
||||
* Returns the result of left rotation of given array arr and integer n
|
||||
*
|
||||
* @param arr : int[] given array
|
||||
*
|
||||
* @param n : int given integer
|
||||
*
|
||||
* @return : int[] result of left rotation
|
||||
*/
|
||||
public static int[] rotateLeft(int[] arr, int n) {
|
||||
int size = arr.length;
|
||||
int[] dst = new int[size];
|
||||
n = n % size;
|
||||
for(int i = 0; i < size; i++) {
|
||||
dst[i] = arr[n];
|
||||
n = (n + 1) % size;
|
||||
}
|
||||
return dst;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the result of left rotation of given array arr and integer n
|
||||
*
|
||||
* @param arr : int[] given array
|
||||
*
|
||||
* @param n : int given integer
|
||||
*
|
||||
* @return : int[] result of left rotation
|
||||
*/
|
||||
public static int[] rotateLeft(int[] arr, int n) {
|
||||
int size = arr.length;
|
||||
int[] dst = new int[size];
|
||||
n = n % size;
|
||||
for (int i = 0; i < size; i++) {
|
||||
dst[i] = arr[n];
|
||||
n = (n + 1) % size;
|
||||
}
|
||||
return dst;
|
||||
}
|
||||
}
|
||||
|
@ -66,7 +66,8 @@ public class BFPRT {
|
||||
int offset = num % 5 == 0 ? 0 : 1;
|
||||
int[] mArr = new int[num / 5 + offset];
|
||||
for (int i = 0; i < mArr.length; i++) {
|
||||
mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4));
|
||||
mArr[i] =
|
||||
getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4));
|
||||
}
|
||||
return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2);
|
||||
}
|
||||
@ -119,7 +120,27 @@ public class BFPRT {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9};
|
||||
int[] arr = {
|
||||
11,
|
||||
9,
|
||||
1,
|
||||
3,
|
||||
9,
|
||||
2,
|
||||
2,
|
||||
5,
|
||||
6,
|
||||
5,
|
||||
3,
|
||||
5,
|
||||
9,
|
||||
7,
|
||||
2,
|
||||
5,
|
||||
5,
|
||||
1,
|
||||
9,
|
||||
};
|
||||
int[] minK = getMinKNumsByBFPRT(arr, 5);
|
||||
System.out.println(Arrays.toString(minK));
|
||||
}
|
||||
|
@ -25,7 +25,13 @@ public class BankersAlgorithm {
|
||||
/**
|
||||
* This method finds the need of each process
|
||||
*/
|
||||
static void calculateNeed(int needArray[][], int maxArray[][], int allocationArray[][], int totalProcess, int totalResources) {
|
||||
static void calculateNeed(
|
||||
int needArray[][],
|
||||
int maxArray[][],
|
||||
int allocationArray[][],
|
||||
int totalProcess,
|
||||
int totalResources
|
||||
) {
|
||||
for (int i = 0; i < totalProcess; i++) {
|
||||
for (int j = 0; j < totalResources; j++) {
|
||||
needArray[i][j] = maxArray[i][j] - allocationArray[i][j];
|
||||
@ -48,10 +54,23 @@ public class BankersAlgorithm {
|
||||
*
|
||||
* @return boolean if the system is in safe state or not
|
||||
*/
|
||||
static boolean checkSafeSystem(int processes[], int availableArray[], int maxArray[][], int allocationArray[][], int totalProcess, int totalResources) {
|
||||
static boolean checkSafeSystem(
|
||||
int processes[],
|
||||
int availableArray[],
|
||||
int maxArray[][],
|
||||
int allocationArray[][],
|
||||
int totalProcess,
|
||||
int totalResources
|
||||
) {
|
||||
int[][] needArray = new int[totalProcess][totalResources];
|
||||
|
||||
calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources);
|
||||
calculateNeed(
|
||||
needArray,
|
||||
maxArray,
|
||||
allocationArray,
|
||||
totalProcess,
|
||||
totalResources
|
||||
);
|
||||
|
||||
boolean[] finishProcesses = new boolean[totalProcess];
|
||||
|
||||
@ -94,12 +113,16 @@ public class BankersAlgorithm {
|
||||
|
||||
// If we could not find a next process in safe sequence.
|
||||
if (foundSafeSystem == false) {
|
||||
System.out.print("The system is not in the safe state because lack of resources");
|
||||
System.out.print(
|
||||
"The system is not in the safe state because lack of resources"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.print("The system is in safe sequence and the sequence is as follows: ");
|
||||
System.out.print(
|
||||
"The system is in safe sequence and the sequence is as follows: "
|
||||
);
|
||||
for (int i = 0; i < totalProcess; i++) {
|
||||
System.out.print("P" + safeSequenceArray[i] + " ");
|
||||
}
|
||||
@ -140,7 +163,9 @@ public class BankersAlgorithm {
|
||||
for (int i = 0; i < numberOfProcesses; i++) {
|
||||
System.out.println("For process " + i + ": ");
|
||||
for (int j = 0; j < numberOfResources; j++) {
|
||||
System.out.println("Enter the maximum instances of resource " + j);
|
||||
System.out.println(
|
||||
"Enter the maximum instances of resource " + j
|
||||
);
|
||||
maxArray[i][j] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
@ -156,12 +181,18 @@ public class BankersAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, numberOfResources);
|
||||
checkSafeSystem(
|
||||
processes,
|
||||
availableArray,
|
||||
maxArray,
|
||||
allocationArray,
|
||||
numberOfProcesses,
|
||||
numberOfResources
|
||||
);
|
||||
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Example:
|
||||
n = 5
|
||||
|
@ -43,6 +43,5 @@ public class BoyerMoore {
|
||||
a[i] = input.nextInt();
|
||||
}
|
||||
System.out.println("the majority element is " + findmajor(a));
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -9,7 +9,9 @@ public class CountChar {
|
||||
System.out.print("Enter your text: ");
|
||||
String str = input.nextLine();
|
||||
input.close();
|
||||
System.out.println("There are " + CountCharacters(str) + " characters.");
|
||||
System.out.println(
|
||||
"There are " + CountCharacters(str) + " characters."
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -16,7 +16,9 @@ public class CountWords {
|
||||
String str = input.nextLine();
|
||||
|
||||
System.out.println("Your text has " + wordCount(str) + " word(s)");
|
||||
System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");
|
||||
System.out.println(
|
||||
"Your text has " + secondaryWordCount(str) + " word(s)"
|
||||
);
|
||||
input.close();
|
||||
}
|
||||
|
||||
|
@ -24,16 +24,16 @@ public class Damm {
|
||||
* calculation.
|
||||
*/
|
||||
private static final byte[][] DAMM_TABLE = {
|
||||
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
|
||||
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
|
||||
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
|
||||
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
|
||||
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
|
||||
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
|
||||
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
|
||||
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
|
||||
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
|
||||
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0}
|
||||
{ 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 },
|
||||
{ 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 },
|
||||
{ 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 },
|
||||
{ 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 },
|
||||
{ 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 },
|
||||
{ 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 },
|
||||
{ 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 },
|
||||
{ 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 },
|
||||
{ 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 },
|
||||
{ 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 },
|
||||
};
|
||||
|
||||
/**
|
||||
@ -92,27 +92,31 @@ public class Damm {
|
||||
}
|
||||
|
||||
private static void checkAndPrint(String input) {
|
||||
String validationResult = Damm.dammCheck(input)
|
||||
? "valid"
|
||||
: "not valid";
|
||||
String validationResult = Damm.dammCheck(input) ? "valid" : "not valid";
|
||||
System.out.println("Input '" + input + "' is " + validationResult);
|
||||
}
|
||||
|
||||
private static void generateAndPrint(String input) {
|
||||
String result = addDammChecksum(input);
|
||||
System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'");
|
||||
System.out.println(
|
||||
"Generate and add checksum to initial value '" +
|
||||
input +
|
||||
"'. Result: '" +
|
||||
result +
|
||||
"'"
|
||||
);
|
||||
}
|
||||
|
||||
private static void checkInput(String input) {
|
||||
Objects.requireNonNull(input);
|
||||
if (!input.matches("\\d+")) {
|
||||
throw new IllegalArgumentException("Input '" + input + "' contains not only digits");
|
||||
throw new IllegalArgumentException(
|
||||
"Input '" + input + "' contains not only digits"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static int[] toIntArray(String string) {
|
||||
return string.chars()
|
||||
.map(i -> Character.digit(i, 10))
|
||||
.toArray();
|
||||
return string.chars().map(i -> Character.digit(i, 10)).toArray();
|
||||
}
|
||||
}
|
||||
|
@ -31,7 +31,8 @@ public class Dijkstra {
|
||||
new Graph.Edge("c", "d", 11),
|
||||
new Graph.Edge("c", "f", 2),
|
||||
new Graph.Edge("d", "e", 6),
|
||||
new Graph.Edge("e", "f", 9),};
|
||||
new Graph.Edge("e", "f", 9),
|
||||
};
|
||||
private static final String START = "a";
|
||||
private static final String END = "e";
|
||||
|
||||
@ -47,6 +48,7 @@ public class Dijkstra {
|
||||
}
|
||||
|
||||
class Graph {
|
||||
|
||||
// mapping of vertex names to Vertex objects, built from a set of Edges
|
||||
|
||||
private final Map<String, Vertex> graph;
|
||||
@ -117,13 +119,23 @@ class Graph {
|
||||
if (dist != vertex.dist) {
|
||||
return false;
|
||||
}
|
||||
if (name != null ? !name.equals(vertex.name) : vertex.name != null) {
|
||||
if (
|
||||
name != null ? !name.equals(vertex.name) : vertex.name != null
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) {
|
||||
if (
|
||||
previous != null
|
||||
? !previous.equals(vertex.previous)
|
||||
: vertex.previous != null
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) {
|
||||
if (
|
||||
neighbours != null
|
||||
? !neighbours.equals(vertex.neighbours)
|
||||
: vertex.neighbours != null
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -136,7 +148,8 @@ class Graph {
|
||||
result = 31 * result + (name != null ? name.hashCode() : 0);
|
||||
result = 31 * result + dist;
|
||||
result = 31 * result + (previous != null ? previous.hashCode() : 0);
|
||||
result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0);
|
||||
result =
|
||||
31 * result + (neighbours != null ? neighbours.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -175,7 +188,10 @@ class Graph {
|
||||
*/
|
||||
public void dijkstra(String startName) {
|
||||
if (!graph.containsKey(startName)) {
|
||||
System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName);
|
||||
System.err.printf(
|
||||
"Graph doesn't contain start vertex \"%s\"%n",
|
||||
startName
|
||||
);
|
||||
return;
|
||||
}
|
||||
final Vertex source = graph.get(startName);
|
||||
@ -222,7 +238,10 @@ class Graph {
|
||||
*/
|
||||
public void printPath(String endName) {
|
||||
if (!graph.containsKey(endName)) {
|
||||
System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName);
|
||||
System.err.printf(
|
||||
"Graph doesn't contain end vertex \"%s\"%n",
|
||||
endName
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -7,6 +7,7 @@ package com.thealgorithms.others;
|
||||
* See https://en.wikipedia.org/wiki/Euler%27s_totient_function
|
||||
*/
|
||||
public class EulersFunction {
|
||||
|
||||
// This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time
|
||||
// complexity;
|
||||
|
||||
|
@ -6,7 +6,9 @@ class FloydTriangle {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
|
||||
System.out.println(
|
||||
"Enter the number of rows which you want in your Floyd Triangle: "
|
||||
);
|
||||
int r = sc.nextInt(), n = 0;
|
||||
sc.close();
|
||||
for (int i = 0; i < r; i++) {
|
||||
|
@ -16,7 +16,7 @@ public class GuassLegendre {
|
||||
|
||||
static double pi(int l) {
|
||||
/*
|
||||
* l: No of loops to run
|
||||
* l: No of loops to run
|
||||
*/
|
||||
|
||||
double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
|
||||
|
@ -6,7 +6,10 @@ import java.util.Scanner;
|
||||
import java.util.Set;
|
||||
|
||||
public class HappyNumbersSeq {
|
||||
private static final Set<Integer> CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
|
||||
|
||||
private static final Set<Integer> CYCLE_NUMS = new HashSet<>(
|
||||
Arrays.asList(4, 16, 20, 37, 58, 145)
|
||||
);
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
@ -1,11 +1,11 @@
|
||||
package com.thealgorithms.others;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Scanner;
|
||||
import java.util.Comparator;
|
||||
|
||||
// node class is the basic structure
|
||||
// of each node present in the Huffman - tree.
|
||||
// node class is the basic structure
|
||||
// of each node present in the Huffman - tree.
|
||||
class HuffmanNode {
|
||||
|
||||
int data;
|
||||
@ -15,67 +15,64 @@ class HuffmanNode {
|
||||
HuffmanNode right;
|
||||
}
|
||||
|
||||
// comparator class helps to compare the node
|
||||
// on the basis of one of its attribute.
|
||||
// Here we will be compared
|
||||
// on the basis of data values of the nodes.
|
||||
// comparator class helps to compare the node
|
||||
// on the basis of one of its attribute.
|
||||
// Here we will be compared
|
||||
// on the basis of data values of the nodes.
|
||||
class MyComparator implements Comparator<HuffmanNode> {
|
||||
|
||||
public int compare(HuffmanNode x, HuffmanNode y) {
|
||||
|
||||
return x.data - y.data;
|
||||
}
|
||||
}
|
||||
|
||||
public class Huffman {
|
||||
|
||||
// recursive function to print the
|
||||
// huffman-code through the tree traversal.
|
||||
// Here s is the huffman - code generated.
|
||||
// recursive function to print the
|
||||
// huffman-code through the tree traversal.
|
||||
// Here s is the huffman - code generated.
|
||||
public static void printCode(HuffmanNode root, String s) {
|
||||
|
||||
// base case; if the left and right are null
|
||||
// then its a leaf node and we print
|
||||
// the code s generated by traversing the tree.
|
||||
if (root.left
|
||||
== null
|
||||
&& root.right
|
||||
== null
|
||||
&& Character.isLetter(root.c)) {
|
||||
|
||||
// c is the character in the node
|
||||
// base case; if the left and right are null
|
||||
// then its a leaf node and we print
|
||||
// the code s generated by traversing the tree.
|
||||
if (
|
||||
root.left == null &&
|
||||
root.right == null &&
|
||||
Character.isLetter(root.c)
|
||||
) {
|
||||
// c is the character in the node
|
||||
System.out.println(root.c + ":" + s);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// if we go to left then add "0" to the code.
|
||||
// if we go to the right add"1" to the code.
|
||||
// recursive calls for left and
|
||||
// right sub-tree of the generated tree.
|
||||
// if we go to left then add "0" to the code.
|
||||
// if we go to the right add"1" to the code.
|
||||
// recursive calls for left and
|
||||
// right sub-tree of the generated tree.
|
||||
printCode(root.left, s + "0");
|
||||
printCode(root.right, s + "1");
|
||||
}
|
||||
|
||||
// main function
|
||||
// main function
|
||||
public static void main(String[] args) {
|
||||
|
||||
Scanner s = new Scanner(System.in);
|
||||
|
||||
// number of characters.
|
||||
// number of characters.
|
||||
int n = 6;
|
||||
char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
|
||||
int[] charfreq = {5, 9, 12, 13, 16, 45};
|
||||
char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
int[] charfreq = { 5, 9, 12, 13, 16, 45 };
|
||||
|
||||
// creating a priority queue q.
|
||||
// makes a min-priority queue(min-heap).
|
||||
PriorityQueue<HuffmanNode> q
|
||||
= new PriorityQueue<HuffmanNode>(n, new MyComparator());
|
||||
// creating a priority queue q.
|
||||
// makes a min-priority queue(min-heap).
|
||||
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(
|
||||
n,
|
||||
new MyComparator()
|
||||
);
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
|
||||
// creating a Huffman node object
|
||||
// and add it to the priority queue.
|
||||
// creating a Huffman node object
|
||||
// and add it to the priority queue.
|
||||
HuffmanNode hn = new HuffmanNode();
|
||||
|
||||
hn.c = charArray[i];
|
||||
@ -84,50 +81,49 @@ public class Huffman {
|
||||
hn.left = null;
|
||||
hn.right = null;
|
||||
|
||||
// add functions adds
|
||||
// the huffman node to the queue.
|
||||
// add functions adds
|
||||
// the huffman node to the queue.
|
||||
q.add(hn);
|
||||
}
|
||||
|
||||
// create a root node
|
||||
// create a root node
|
||||
HuffmanNode root = null;
|
||||
|
||||
// Here we will extract the two minimum value
|
||||
// from the heap each time until
|
||||
// its size reduces to 1, extract until
|
||||
// all the nodes are extracted.
|
||||
// Here we will extract the two minimum value
|
||||
// from the heap each time until
|
||||
// its size reduces to 1, extract until
|
||||
// all the nodes are extracted.
|
||||
while (q.size() > 1) {
|
||||
|
||||
// first min extract.
|
||||
// first min extract.
|
||||
HuffmanNode x = q.peek();
|
||||
q.poll();
|
||||
|
||||
// second min extarct.
|
||||
// second min extarct.
|
||||
HuffmanNode y = q.peek();
|
||||
q.poll();
|
||||
|
||||
// new node f which is equal
|
||||
// new node f which is equal
|
||||
HuffmanNode f = new HuffmanNode();
|
||||
|
||||
// to the sum of the frequency of the two nodes
|
||||
// assigning values to the f node.
|
||||
// to the sum of the frequency of the two nodes
|
||||
// assigning values to the f node.
|
||||
f.data = x.data + y.data;
|
||||
f.c = '-';
|
||||
|
||||
// first extracted node as left child.
|
||||
// first extracted node as left child.
|
||||
f.left = x;
|
||||
|
||||
// second extracted node as the right child.
|
||||
// second extracted node as the right child.
|
||||
f.right = y;
|
||||
|
||||
// marking the f node as the root node.
|
||||
// marking the f node as the root node.
|
||||
root = f;
|
||||
|
||||
// add this node to the priority-queue.
|
||||
// add this node to the priority-queue.
|
||||
q.add(f);
|
||||
}
|
||||
|
||||
// print the codes by traversing the tree
|
||||
// print the codes by traversing the tree
|
||||
printCode(root, "");
|
||||
}
|
||||
}
|
||||
|
@ -1,23 +1,23 @@
|
||||
package com.thealgorithms.others;
|
||||
|
||||
// Java Program to implement Auto-Complete
|
||||
// Java Program to implement Auto-Complete
|
||||
// Feature using Trie
|
||||
class Trieac {
|
||||
|
||||
// Alphabet size (# of symbols)
|
||||
// Alphabet size (# of symbols)
|
||||
public static final int ALPHABET_SIZE = 26;
|
||||
|
||||
// Trie node
|
||||
// Trie node
|
||||
static class TrieNode {
|
||||
|
||||
TrieNode children[] = new TrieNode[ALPHABET_SIZE];
|
||||
|
||||
// isWordEnd is true if the node represents
|
||||
// end of a word
|
||||
// isWordEnd is true if the node represents
|
||||
// end of a word
|
||||
boolean isWordEnd;
|
||||
};
|
||||
}
|
||||
|
||||
// Returns new trie node (initialized to NULLs)
|
||||
// Returns new trie node (initialized to NULLs)
|
||||
static TrieNode getNode() {
|
||||
TrieNode pNode = new TrieNode();
|
||||
pNode.isWordEnd = false;
|
||||
@ -29,8 +29,8 @@ class Trieac {
|
||||
return pNode;
|
||||
}
|
||||
|
||||
// If not present, inserts key into trie. If the
|
||||
// key is prefix of trie node, just marks leaf node
|
||||
// If not present, inserts key into trie. If the
|
||||
// key is prefix of trie node, just marks leaf node
|
||||
static void insert(TrieNode root, final String key) {
|
||||
TrieNode pCrawl = root;
|
||||
|
||||
@ -42,11 +42,11 @@ class Trieac {
|
||||
pCrawl = pCrawl.children[index];
|
||||
}
|
||||
|
||||
// mark last node as leaf
|
||||
// mark last node as leaf
|
||||
pCrawl.isWordEnd = true;
|
||||
}
|
||||
|
||||
// Returns true if key presents in trie, else false
|
||||
// Returns true if key presents in trie, else false
|
||||
boolean search(TrieNode root, final String key) {
|
||||
int length = key.length();
|
||||
TrieNode pCrawl = root;
|
||||
@ -62,8 +62,8 @@ class Trieac {
|
||||
return (pCrawl != null && pCrawl.isWordEnd);
|
||||
}
|
||||
|
||||
// Returns 0 if current node has a child
|
||||
// If all children are NULL, return 1.
|
||||
// Returns 0 if current node has a child
|
||||
// If all children are NULL, return 1.
|
||||
static boolean isLastNode(TrieNode root) {
|
||||
for (int i = 0; i < ALPHABET_SIZE; i++) {
|
||||
if (root.children[i] != null) {
|
||||
@ -73,25 +73,25 @@ class Trieac {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Recursive function to print auto-suggestions
|
||||
// for given node.
|
||||
// Recursive function to print auto-suggestions
|
||||
// for given node.
|
||||
static void suggestionsRec(TrieNode root, String currPrefix) {
|
||||
// found a string in Trie with the given prefix
|
||||
// found a string in Trie with the given prefix
|
||||
if (root.isWordEnd) {
|
||||
System.out.println(currPrefix);
|
||||
}
|
||||
|
||||
// All children struct node pointers are NULL
|
||||
// All children struct node pointers are NULL
|
||||
if (isLastNode(root)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < ALPHABET_SIZE; i++) {
|
||||
if (root.children[i] != null) {
|
||||
// append current character to currPrefix string
|
||||
// append current character to currPrefix string
|
||||
currPrefix += (char) (97 + i);
|
||||
|
||||
// recur over the rest
|
||||
// recur over the rest
|
||||
suggestionsRec(root.children[i], currPrefix);
|
||||
}
|
||||
}
|
||||
@ -99,20 +99,19 @@ class Trieac {
|
||||
|
||||
// Fucntion to print suggestions for
|
||||
// given query prefix.
|
||||
static int printAutoSuggestions(TrieNode root,
|
||||
final String query) {
|
||||
static int printAutoSuggestions(TrieNode root, final String query) {
|
||||
TrieNode pCrawl = root;
|
||||
|
||||
// Check if prefix is present and find the
|
||||
// the node (of last level) with last character
|
||||
// of given string.
|
||||
// Check if prefix is present and find the
|
||||
// the node (of last level) with last character
|
||||
// of given string.
|
||||
int level;
|
||||
int n = query.length();
|
||||
|
||||
for (level = 0; level < n; level++) {
|
||||
int index = (query.charAt(level) - 'a');
|
||||
|
||||
// no string in the Trie has this prefix
|
||||
// no string in the Trie has this prefix
|
||||
if (pCrawl.children[index] == null) {
|
||||
return 0;
|
||||
}
|
||||
@ -120,23 +119,23 @@ class Trieac {
|
||||
pCrawl = pCrawl.children[index];
|
||||
}
|
||||
|
||||
// If prefix is present as a word.
|
||||
// If prefix is present as a word.
|
||||
boolean isWord = (pCrawl.isWordEnd == true);
|
||||
|
||||
// If prefix is last node of tree (has no
|
||||
// children)
|
||||
// If prefix is last node of tree (has no
|
||||
// children)
|
||||
boolean isLast = isLastNode(pCrawl);
|
||||
|
||||
// If prefix is present as a word, but
|
||||
// there is no subtree below the last
|
||||
// matching node.
|
||||
// If prefix is present as a word, but
|
||||
// there is no subtree below the last
|
||||
// matching node.
|
||||
if (isWord && isLast) {
|
||||
System.out.println(query);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// If there are nodes below the last
|
||||
// matching character.
|
||||
// If there are nodes below the last
|
||||
// matching character.
|
||||
if (!isLast) {
|
||||
String prefix = query;
|
||||
suggestionsRec(pCrawl, prefix);
|
||||
@ -161,11 +160,11 @@ class Trieac {
|
||||
int comp = printAutoSuggestions(root, "hel");
|
||||
|
||||
if (comp == -1) {
|
||||
System.out.println("No other strings found "
|
||||
+ "with this prefix\n");
|
||||
System.out.println(
|
||||
"No other strings found " + "with this prefix\n"
|
||||
);
|
||||
} else if (comp == 0) {
|
||||
System.out.println("No string found with"
|
||||
+ " this prefix\n");
|
||||
System.out.println("No string found with" + " this prefix\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,9 @@ public class InsertDeleteInArray {
|
||||
}
|
||||
|
||||
// To insert a new element(we are creating a new array)
|
||||
System.out.println("Enter the index at which the element should be inserted");
|
||||
System.out.println(
|
||||
"Enter the index at which the element should be inserted"
|
||||
);
|
||||
int insert_pos = s.nextInt();
|
||||
System.out.println("Enter the element to be inserted");
|
||||
int ins = s.nextInt();
|
||||
|
@ -5,6 +5,7 @@ package com.thealgorithms.others;
|
||||
* for an example
|
||||
*/
|
||||
public class KMP {
|
||||
|
||||
// a working example
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -56,7 +56,8 @@ public class KochSnowflake {
|
||||
assert image.getRGB(0, 0) == new Color(255, 255, 255).getRGB();
|
||||
|
||||
// The snowflake is drawn in black and this is the position of the first vector
|
||||
assert image.getRGB((int) offsetX, (int) offsetY) == new Color(0, 0, 0).getRGB();
|
||||
assert image.getRGB((int) offsetX, (int) offsetY) ==
|
||||
new Color(0, 0, 0).getRGB();
|
||||
|
||||
// Save image
|
||||
try {
|
||||
@ -76,7 +77,10 @@ public class KochSnowflake {
|
||||
* @param steps The number of iterations.
|
||||
* @return The transformed vectors after the iteration-steps.
|
||||
*/
|
||||
public static ArrayList<Vector2> Iterate(ArrayList<Vector2> initialVectors, int steps) {
|
||||
public static ArrayList<Vector2> Iterate(
|
||||
ArrayList<Vector2> initialVectors,
|
||||
int steps
|
||||
) {
|
||||
ArrayList<Vector2> vectors = initialVectors;
|
||||
for (int i = 0; i < steps; i++) {
|
||||
vectors = IterationStep(vectors);
|
||||
@ -94,14 +98,18 @@ public class KochSnowflake {
|
||||
*/
|
||||
public static BufferedImage GetKochSnowflake(int imageWidth, int steps) {
|
||||
if (imageWidth <= 0) {
|
||||
throw new IllegalArgumentException("imageWidth should be greater than zero");
|
||||
throw new IllegalArgumentException(
|
||||
"imageWidth should be greater than zero"
|
||||
);
|
||||
}
|
||||
|
||||
double offsetX = imageWidth / 10.;
|
||||
double offsetY = imageWidth / 3.7;
|
||||
Vector2 vector1 = new Vector2(offsetX, offsetY);
|
||||
Vector2 vector2
|
||||
= new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY);
|
||||
Vector2 vector2 = new Vector2(
|
||||
imageWidth / 2,
|
||||
Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY
|
||||
);
|
||||
Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY);
|
||||
ArrayList<Vector2> initialVectors = new ArrayList<Vector2>();
|
||||
initialVectors.add(vector1);
|
||||
@ -122,15 +130,23 @@ public class KochSnowflake {
|
||||
* applied.
|
||||
* @return The transformed vectors after the iteration-step.
|
||||
*/
|
||||
private static ArrayList<Vector2> IterationStep(ArrayList<Vector2> vectors) {
|
||||
private static ArrayList<Vector2> IterationStep(
|
||||
ArrayList<Vector2> vectors
|
||||
) {
|
||||
ArrayList<Vector2> newVectors = new ArrayList<Vector2>();
|
||||
for (int i = 0; i < vectors.size() - 1; i++) {
|
||||
Vector2 startVector = vectors.get(i);
|
||||
Vector2 endVector = vectors.get(i + 1);
|
||||
newVectors.add(startVector);
|
||||
Vector2 differenceVector = endVector.subtract(startVector).multiply(1. / 3);
|
||||
Vector2 differenceVector = endVector
|
||||
.subtract(startVector)
|
||||
.multiply(1. / 3);
|
||||
newVectors.add(startVector.add(differenceVector));
|
||||
newVectors.add(startVector.add(differenceVector).add(differenceVector.rotate(60)));
|
||||
newVectors.add(
|
||||
startVector
|
||||
.add(differenceVector)
|
||||
.add(differenceVector.rotate(60))
|
||||
);
|
||||
newVectors.add(startVector.add(differenceVector.multiply(2)));
|
||||
}
|
||||
|
||||
@ -147,8 +163,15 @@ public class KochSnowflake {
|
||||
* @return The image of the rendered edges.
|
||||
*/
|
||||
private static BufferedImage GetImage(
|
||||
ArrayList<Vector2> vectors, int imageWidth, int imageHeight) {
|
||||
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
|
||||
ArrayList<Vector2> vectors,
|
||||
int imageWidth,
|
||||
int imageHeight
|
||||
) {
|
||||
BufferedImage image = new BufferedImage(
|
||||
imageWidth,
|
||||
imageHeight,
|
||||
BufferedImage.TYPE_INT_RGB
|
||||
);
|
||||
Graphics2D g2d = image.createGraphics();
|
||||
|
||||
// Set the background white
|
||||
|
@ -21,7 +21,11 @@ public class LinearCongruentialGenerator {
|
||||
* @param modulo The maximum number that can be generated (exclusive). A
|
||||
* common value is 2^32.
|
||||
*/
|
||||
public LinearCongruentialGenerator(double multiplier, double increment, double modulo) {
|
||||
public LinearCongruentialGenerator(
|
||||
double multiplier,
|
||||
double increment,
|
||||
double modulo
|
||||
) {
|
||||
this(System.currentTimeMillis(), multiplier, increment, modulo);
|
||||
}
|
||||
|
||||
@ -36,7 +40,11 @@ public class LinearCongruentialGenerator {
|
||||
* common value is 2^32.
|
||||
*/
|
||||
public LinearCongruentialGenerator(
|
||||
double seed, double multiplier, double increment, double modulo) {
|
||||
double seed,
|
||||
double multiplier,
|
||||
double increment,
|
||||
double modulo
|
||||
) {
|
||||
this.previousValue = seed;
|
||||
this.a = multiplier;
|
||||
this.c = increment;
|
||||
@ -58,8 +66,11 @@ public class LinearCongruentialGenerator {
|
||||
// Show the LCG in action.
|
||||
// Decisive proof that the LCG works could be made by adding each number
|
||||
// generated to a Set while checking for duplicates.
|
||||
LinearCongruentialGenerator lcg
|
||||
= new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
|
||||
LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(
|
||||
1664525,
|
||||
1013904223,
|
||||
Math.pow(2.0, 32.0)
|
||||
);
|
||||
for (int i = 0; i < 512; i++) {
|
||||
System.out.println(lcg.nextNumber());
|
||||
}
|
||||
|
@ -29,8 +29,12 @@ public class LowestBasePalindrome {
|
||||
in.next();
|
||||
}
|
||||
}
|
||||
System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n));
|
||||
System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n)));
|
||||
System.out.println(
|
||||
n + " is a palindrome in base " + lowestBasePalindrome(n)
|
||||
);
|
||||
System.out.println(
|
||||
base2base(Integer.toString(n), 10, lowestBasePalindrome(n))
|
||||
);
|
||||
in.close();
|
||||
}
|
||||
|
||||
|
@ -67,8 +67,8 @@ public class Luhn {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Luhn algorithm usage examples:");
|
||||
int[] validInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7};
|
||||
int[] invalidInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4}; //typo in last symbol
|
||||
int[] validInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7 };
|
||||
int[] invalidInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4 }; //typo in last symbol
|
||||
checkAndPrint(validInput);
|
||||
checkAndPrint(invalidInput);
|
||||
|
||||
@ -82,13 +82,12 @@ public class Luhn {
|
||||
}
|
||||
|
||||
private static void checkAndPrint(int[] input) {
|
||||
String validationResult = Luhn.luhnCheck(input)
|
||||
? "valid"
|
||||
: "not valid";
|
||||
System.out.println("Input " + Arrays.toString(input) + " is " + validationResult);
|
||||
String validationResult = Luhn.luhnCheck(input) ? "valid" : "not valid";
|
||||
System.out.println(
|
||||
"Input " + Arrays.toString(input) + " is " + validationResult
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
========================
|
||||
Business usage example
|
||||
@ -98,7 +97,6 @@ public class Luhn {
|
||||
* Object representation of credit card.
|
||||
*/
|
||||
private record CreditCard(int[] digits) {
|
||||
|
||||
private static final int DIGITS_COUNT = 16;
|
||||
|
||||
/**
|
||||
@ -111,14 +109,21 @@ public class Luhn {
|
||||
public static CreditCard fromString(String cardNumber) {
|
||||
Objects.requireNonNull(cardNumber);
|
||||
String trimmedCardNumber = cardNumber.replaceAll(" ", "");
|
||||
if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) {
|
||||
throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number");
|
||||
if (
|
||||
trimmedCardNumber.length() != DIGITS_COUNT ||
|
||||
!trimmedCardNumber.matches("\\d+")
|
||||
) {
|
||||
throw new IllegalArgumentException(
|
||||
"{" + cardNumber + "} - is not a card number"
|
||||
);
|
||||
}
|
||||
|
||||
int[] cardNumbers = toIntArray(trimmedCardNumber);
|
||||
boolean isValid = luhnCheck(cardNumbers);
|
||||
if (!isValid) {
|
||||
throw new IllegalArgumentException("Credit card number {" + cardNumber + "} - have a typo");
|
||||
throw new IllegalArgumentException(
|
||||
"Credit card number {" + cardNumber + "} - have a typo"
|
||||
);
|
||||
}
|
||||
|
||||
return new CreditCard(cardNumbers);
|
||||
@ -141,23 +146,34 @@ public class Luhn {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s {%s}", CreditCard.class.getSimpleName(), number());
|
||||
return String.format(
|
||||
"%s {%s}",
|
||||
CreditCard.class.getSimpleName(),
|
||||
number()
|
||||
);
|
||||
}
|
||||
|
||||
private static int[] toIntArray(String string) {
|
||||
return string.chars()
|
||||
.map(i -> Character.digit(i, 10))
|
||||
.toArray();
|
||||
return string.chars().map(i -> Character.digit(i, 10)).toArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static void businessExample(String cardNumber) {
|
||||
try {
|
||||
System.out.println("Trying to create CreditCard object from valid card number: " + cardNumber);
|
||||
System.out.println(
|
||||
"Trying to create CreditCard object from valid card number: " +
|
||||
cardNumber
|
||||
);
|
||||
CreditCard creditCard = CreditCard.fromString(cardNumber);
|
||||
System.out.println("And business object is successfully created: " + creditCard + "\n");
|
||||
System.out.println(
|
||||
"And business object is successfully created: " +
|
||||
creditCard +
|
||||
"\n"
|
||||
);
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.out.println("And fail with exception message: " + e.getMessage() + "\n");
|
||||
System.out.println(
|
||||
"And fail with exception message: " + e.getMessage() + "\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -27,13 +27,23 @@ public class Mandelbrot {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Test black and white
|
||||
BufferedImage blackAndWhiteImage = getImage(800, 600, -0.6, 0, 3.2, 50, false);
|
||||
BufferedImage blackAndWhiteImage = getImage(
|
||||
800,
|
||||
600,
|
||||
-0.6,
|
||||
0,
|
||||
3.2,
|
||||
50,
|
||||
false
|
||||
);
|
||||
|
||||
// Pixel outside the Mandelbrot set should be white.
|
||||
assert blackAndWhiteImage.getRGB(0, 0) == new Color(255, 255, 255).getRGB();
|
||||
assert blackAndWhiteImage.getRGB(0, 0) ==
|
||||
new Color(255, 255, 255).getRGB();
|
||||
|
||||
// Pixel inside the Mandelbrot set should be black.
|
||||
assert blackAndWhiteImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB();
|
||||
assert blackAndWhiteImage.getRGB(400, 300) ==
|
||||
new Color(0, 0, 0).getRGB();
|
||||
|
||||
// Test color-coding
|
||||
BufferedImage coloredImage = getImage(800, 600, -0.6, 0, 3.2, 50, true);
|
||||
@ -71,44 +81,62 @@ public class Mandelbrot {
|
||||
* @return The image of the rendered Mandelbrot set.
|
||||
*/
|
||||
public static BufferedImage getImage(
|
||||
int imageWidth,
|
||||
int imageHeight,
|
||||
double figureCenterX,
|
||||
double figureCenterY,
|
||||
double figureWidth,
|
||||
int maxStep,
|
||||
boolean useDistanceColorCoding) {
|
||||
int imageWidth,
|
||||
int imageHeight,
|
||||
double figureCenterX,
|
||||
double figureCenterY,
|
||||
double figureWidth,
|
||||
int maxStep,
|
||||
boolean useDistanceColorCoding
|
||||
) {
|
||||
if (imageWidth <= 0) {
|
||||
throw new IllegalArgumentException("imageWidth should be greater than zero");
|
||||
throw new IllegalArgumentException(
|
||||
"imageWidth should be greater than zero"
|
||||
);
|
||||
}
|
||||
|
||||
if (imageHeight <= 0) {
|
||||
throw new IllegalArgumentException("imageHeight should be greater than zero");
|
||||
throw new IllegalArgumentException(
|
||||
"imageHeight should be greater than zero"
|
||||
);
|
||||
}
|
||||
|
||||
if (maxStep <= 0) {
|
||||
throw new IllegalArgumentException("maxStep should be greater than zero");
|
||||
throw new IllegalArgumentException(
|
||||
"maxStep should be greater than zero"
|
||||
);
|
||||
}
|
||||
|
||||
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
|
||||
BufferedImage image = new BufferedImage(
|
||||
imageWidth,
|
||||
imageHeight,
|
||||
BufferedImage.TYPE_INT_RGB
|
||||
);
|
||||
double figureHeight = figureWidth / imageWidth * imageHeight;
|
||||
|
||||
// loop through the image-coordinates
|
||||
for (int imageX = 0; imageX < imageWidth; imageX++) {
|
||||
for (int imageY = 0; imageY < imageHeight; imageY++) {
|
||||
// determine the figure-coordinates based on the image-coordinates
|
||||
double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth;
|
||||
double figureY = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight;
|
||||
double figureX =
|
||||
figureCenterX +
|
||||
((double) imageX / imageWidth - 0.5) *
|
||||
figureWidth;
|
||||
double figureY =
|
||||
figureCenterY +
|
||||
((double) imageY / imageHeight - 0.5) *
|
||||
figureHeight;
|
||||
|
||||
double distance = getDistance(figureX, figureY, maxStep);
|
||||
|
||||
// color the corresponding pixel based on the selected coloring-function
|
||||
image.setRGB(
|
||||
imageX,
|
||||
imageY,
|
||||
useDistanceColorCoding
|
||||
? colorCodedColorMap(distance).getRGB()
|
||||
: blackAndWhiteColorMap(distance).getRGB());
|
||||
imageX,
|
||||
imageY,
|
||||
useDistanceColorCoding
|
||||
? colorCodedColorMap(distance).getRGB()
|
||||
: blackAndWhiteColorMap(distance).getRGB()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -177,7 +205,11 @@ public class Mandelbrot {
|
||||
* @param maxStep Maximum number of steps to check for divergent behavior.
|
||||
* @return The relative distance as the ratio of steps taken to maxStep.
|
||||
*/
|
||||
private static double getDistance(double figureX, double figureY, int maxStep) {
|
||||
private static double getDistance(
|
||||
double figureX,
|
||||
double figureY,
|
||||
int maxStep
|
||||
) {
|
||||
double a = figureX;
|
||||
double b = figureY;
|
||||
int currentStep = 0;
|
||||
|
@ -1,4 +1,5 @@
|
||||
package com.thealgorithms.others;
|
||||
|
||||
/**
|
||||
* @author Alexandros Lemonaris
|
||||
*/
|
||||
@ -20,16 +21,19 @@ public abstract class MemoryManagementAlgorithms {
|
||||
* @return the ArrayList filled with Integers repressenting the memory
|
||||
* allocation that took place.
|
||||
*/
|
||||
public abstract ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses);
|
||||
|
||||
public abstract ArrayList<Integer> fitProcess(
|
||||
int[] sizeOfBlocks,
|
||||
int[] sizeOfProcesses
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Dekas Dimitrios
|
||||
*/
|
||||
class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
|
||||
private static final int NO_ALLOCATION
|
||||
= -255; // if a process has been allocated in position -255,
|
||||
private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
|
||||
|
||||
// it means that it has not been actually allocated.
|
||||
|
||||
/**
|
||||
@ -62,13 +66,13 @@ class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
// Initialize minDiff with an unreachable value by a difference between a blockSize and the
|
||||
// processSize.
|
||||
int minDiff = findMaxElement(blockSizes);
|
||||
int index
|
||||
= NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the
|
||||
int index = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the
|
||||
// result.
|
||||
for (int i = 0;
|
||||
i < blockSizes.length;
|
||||
i++) { // Find the most fitting memory block for the given process.
|
||||
if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) {
|
||||
for (int i = 0; i < blockSizes.length; i++) { // Find the most fitting memory block for the given process.
|
||||
if (
|
||||
blockSizes[i] - processSize < minDiff &&
|
||||
blockSizes[i] - processSize >= 0
|
||||
) {
|
||||
minDiff = blockSizes[i] - processSize;
|
||||
index = i;
|
||||
}
|
||||
@ -88,23 +92,22 @@ class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
* @return the ArrayList filled with Integers repressenting the memory
|
||||
* allocation that took place.
|
||||
*/
|
||||
public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) {
|
||||
public ArrayList<Integer> fitProcess(
|
||||
int[] sizeOfBlocks,
|
||||
int[] sizeOfProcesses
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the best-fit algorithm
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx
|
||||
= findBestFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
|
||||
if (chosenBlockIdx
|
||||
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -112,8 +115,8 @@ class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
*/
|
||||
class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
|
||||
private static final int NO_ALLOCATION
|
||||
= -255; // if a process has been allocated in position -255,
|
||||
private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
|
||||
|
||||
// it means that it has not been actually allocated.
|
||||
|
||||
/**
|
||||
@ -128,9 +131,7 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
private static int findWorstFit(int[] blockSizes, int processSize) {
|
||||
int max = -1;
|
||||
int index = -1;
|
||||
for (int i = 0;
|
||||
i < blockSizes.length;
|
||||
i++) { // Find the index of the biggest memory block available.
|
||||
for (int i = 0; i < blockSizes.length; i++) { // Find the index of the biggest memory block available.
|
||||
if (blockSizes[i] > max) {
|
||||
max = blockSizes[i];
|
||||
index = i;
|
||||
@ -155,23 +156,22 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
* @return the ArrayList filled with Integers repressenting the memory
|
||||
* allocation that took place.
|
||||
*/
|
||||
public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) {
|
||||
public ArrayList<Integer> fitProcess(
|
||||
int[] sizeOfBlocks,
|
||||
int[] sizeOfProcesses
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the worst-fit algorithm
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx
|
||||
= findWorstFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
|
||||
if (chosenBlockIdx
|
||||
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -179,8 +179,8 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
*/
|
||||
class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
|
||||
private static final int NO_ALLOCATION
|
||||
= -255; // if a process has been allocated in position -255,
|
||||
private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
|
||||
|
||||
// it means that it has not been actually allocated.
|
||||
|
||||
/**
|
||||
@ -214,23 +214,22 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
* @return the ArrayList filled with Integers repressenting the memory
|
||||
* allocation that took place.
|
||||
*/
|
||||
public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) {
|
||||
public ArrayList<Integer> fitProcess(
|
||||
int[] sizeOfBlocks,
|
||||
int[] sizeOfProcesses
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the first-fit algorithm
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx
|
||||
= findFirstFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
|
||||
if (chosenBlockIdx
|
||||
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -238,10 +237,10 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
*/
|
||||
class NextFit extends MemoryManagementAlgorithms {
|
||||
|
||||
private static final int NO_ALLOCATION
|
||||
= -255; // if a process has been allocated in position -255,
|
||||
private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
|
||||
// it means that it has not been actually allocated.
|
||||
private int counter = 0; // variable that keeps the position of the last registration into the memory
|
||||
|
||||
/**
|
||||
* Method to find the index of the memory block that is going to fit the
|
||||
* given process based on the next fit algorithm. In the case of next fit,
|
||||
@ -253,9 +252,8 @@ class NextFit extends MemoryManagementAlgorithms {
|
||||
* exists.
|
||||
*/
|
||||
private int findNextFit(int[] blockSizes, int processSize) {
|
||||
|
||||
for (int i = 0; i < blockSizes.length; i++) {
|
||||
if (counter + i >= blockSizes.length){
|
||||
if (counter + i >= blockSizes.length) {
|
||||
counter = -i; // starts from the start of the array
|
||||
}
|
||||
if (blockSizes[i + counter] >= processSize) {
|
||||
@ -280,22 +278,20 @@ class NextFit extends MemoryManagementAlgorithms {
|
||||
* @return the ArrayList filled with Integers repressenting the memory
|
||||
* allocation that took place.
|
||||
*/
|
||||
public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) {
|
||||
public ArrayList<Integer> fitProcess(
|
||||
int[] sizeOfBlocks,
|
||||
int[] sizeOfProcesses
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the first-fit algorithm
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx
|
||||
= findNextFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findNextFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
|
||||
if (chosenBlockIdx
|
||||
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -43,7 +43,11 @@ public class MiniMaxAlgorithm {
|
||||
|
||||
System.out.println(Arrays.toString(miniMaxAlgorith.getScores()));
|
||||
System.out.println(
|
||||
"The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + String.valueOf(bestScore));
|
||||
"The best score for " +
|
||||
(isMaximizer ? "Maximizer" : "Minimizer") +
|
||||
" is " +
|
||||
String.valueOf(bestScore)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -55,7 +59,12 @@ public class MiniMaxAlgorithm {
|
||||
* @param verbose True to show each players choices.
|
||||
* @return The optimal score for the player that made the first move.
|
||||
*/
|
||||
public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) {
|
||||
public int miniMax(
|
||||
int depth,
|
||||
boolean isMaximizer,
|
||||
int index,
|
||||
boolean verbose
|
||||
) {
|
||||
int bestScore, score1, score2;
|
||||
|
||||
if (depth == height) { // Leaf node reached.
|
||||
@ -79,8 +88,15 @@ public class MiniMaxAlgorithm {
|
||||
// (1 x 2) = 2; ((1 x 2) + 1) = 3
|
||||
// (2 x 2) = 4; ((2 x 2) + 1) = 5 ...
|
||||
if (verbose) {
|
||||
System.out.println(String.format("From %02d and %02d, %s chooses %02d", score1, score2,
|
||||
(isMaximizer ? "Maximizer" : "Minimizer"), bestScore));
|
||||
System.out.println(
|
||||
String.format(
|
||||
"From %02d and %02d, %s chooses %02d",
|
||||
score1,
|
||||
score2,
|
||||
(isMaximizer ? "Maximizer" : "Minimizer"),
|
||||
bestScore
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return bestScore;
|
||||
|
@ -10,7 +10,9 @@ class PageRank {
|
||||
System.out.print("Enter the Number of WebPages: ");
|
||||
nodes = in.nextInt();
|
||||
PageRank p = new PageRank();
|
||||
System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: ");
|
||||
System.out.println(
|
||||
"Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "
|
||||
);
|
||||
for (i = 1; i <= nodes; i++) {
|
||||
for (j = 1; j <= nodes; j++) {
|
||||
p.path[i][j] = in.nextInt();
|
||||
@ -26,7 +28,6 @@ class PageRank {
|
||||
public double pagerank[] = new double[10];
|
||||
|
||||
public void calc(double totalNodes) {
|
||||
|
||||
double InitialPageRank;
|
||||
double OutgoingLinks = 0;
|
||||
double DampingFactor = 0.85;
|
||||
@ -37,7 +38,12 @@ class PageRank {
|
||||
int ITERATION_STEP = 1;
|
||||
InitialPageRank = 1 / totalNodes;
|
||||
System.out.printf(
|
||||
" Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n");
|
||||
" Total Number of Nodes :" +
|
||||
totalNodes +
|
||||
"\t Initial PageRank of All Nodes :" +
|
||||
InitialPageRank +
|
||||
"\n"
|
||||
);
|
||||
|
||||
// 0th ITERATION _ OR _ INITIALIZATION PHASE //
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
@ -46,20 +52,31 @@ class PageRank {
|
||||
System.out.printf("\n Initial PageRank Values , 0th Step \n");
|
||||
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
|
||||
System.out.printf(
|
||||
" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
while (ITERATION_STEP <= 2) // Iterations
|
||||
{
|
||||
while (ITERATION_STEP <= 2) { // Iterations
|
||||
// Store the PageRank for All Nodes in Temporary Array
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
TempPageRank[k] = this.pagerank[k];
|
||||
this.pagerank[k] = 0;
|
||||
}
|
||||
|
||||
for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) {
|
||||
for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) {
|
||||
if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) {
|
||||
for (
|
||||
InternalNodeNumber = 1;
|
||||
InternalNodeNumber <= totalNodes;
|
||||
InternalNodeNumber++
|
||||
) {
|
||||
for (
|
||||
ExternalNodeNumber = 1;
|
||||
ExternalNodeNumber <= totalNodes;
|
||||
ExternalNodeNumber++
|
||||
) {
|
||||
if (
|
||||
this.path[ExternalNodeNumber][InternalNodeNumber] == 1
|
||||
) {
|
||||
k = 1;
|
||||
OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber
|
||||
while (k <= totalNodes) {
|
||||
@ -69,13 +86,21 @@ class PageRank {
|
||||
k = k + 1;
|
||||
}
|
||||
// Calculate PageRank
|
||||
this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks);
|
||||
this.pagerank[InternalNodeNumber] +=
|
||||
TempPageRank[ExternalNodeNumber] *
|
||||
(1 / OutgoingLinks);
|
||||
}
|
||||
}
|
||||
System.out.printf("\n After " + ITERATION_STEP + "th Step \n");
|
||||
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
|
||||
System.out.printf(
|
||||
" Page Rank of " +
|
||||
k +
|
||||
" is :\t" +
|
||||
this.pagerank[k] +
|
||||
"\n"
|
||||
);
|
||||
}
|
||||
|
||||
ITERATION_STEP = ITERATION_STEP + 1;
|
||||
@ -83,15 +108,17 @@ class PageRank {
|
||||
|
||||
// Add the Damping Factor to PageRank
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k];
|
||||
this.pagerank[k] =
|
||||
(1 - DampingFactor) + DampingFactor * this.pagerank[k];
|
||||
}
|
||||
|
||||
// Display PageRank
|
||||
System.out.printf("\n Final Page Rank : \n");
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
|
||||
System.out.printf(
|
||||
" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -38,7 +38,11 @@ class PasswordGen {
|
||||
StringBuilder password = new StringBuilder();
|
||||
|
||||
// Note that size of the password is also random
|
||||
for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) {
|
||||
for (
|
||||
int i = random.nextInt(max_length - min_length) + min_length;
|
||||
i > 0;
|
||||
--i
|
||||
) {
|
||||
password.append(letters.get(random.nextInt(letters.size())));
|
||||
}
|
||||
|
||||
|
@ -18,7 +18,12 @@ public class PerlinNoise {
|
||||
* @return float array containing calculated "Perlin-Noise" values
|
||||
*/
|
||||
static float[][] generatePerlinNoise(
|
||||
int width, int height, int octaveCount, float persistence, long seed) {
|
||||
int width,
|
||||
int height,
|
||||
int octaveCount,
|
||||
float persistence,
|
||||
long seed
|
||||
) {
|
||||
final float[][] base = new float[width][height];
|
||||
final float[][] perlinNoise = new float[width][height];
|
||||
final float[][][] noiseLayers = new float[octaveCount][][];
|
||||
@ -33,7 +38,8 @@ public class PerlinNoise {
|
||||
|
||||
// calculate octaves with different roughness
|
||||
for (int octave = 0; octave < octaveCount; octave++) {
|
||||
noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave);
|
||||
noiseLayers[octave] =
|
||||
generatePerlinNoiseLayer(base, width, height, octave);
|
||||
}
|
||||
|
||||
float amplitude = 1f;
|
||||
@ -70,7 +76,12 @@ public class PerlinNoise {
|
||||
* @param octave current layer
|
||||
* @return float array containing calculated "Perlin-Noise-Layer" values
|
||||
*/
|
||||
static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) {
|
||||
static float[][] generatePerlinNoiseLayer(
|
||||
float[][] base,
|
||||
int width,
|
||||
int height,
|
||||
int octave
|
||||
) {
|
||||
float[][] perlinNoiseLayer = new float[width][height];
|
||||
|
||||
// calculate period (wavelength) for different shapes
|
||||
@ -90,13 +101,22 @@ public class PerlinNoise {
|
||||
float verticalBlend = (y - y0) * frequency;
|
||||
|
||||
// blend top corners
|
||||
float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend);
|
||||
float top = interpolate(
|
||||
base[x0][y0],
|
||||
base[x1][y0],
|
||||
horizintalBlend
|
||||
);
|
||||
|
||||
// blend bottom corners
|
||||
float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend);
|
||||
float bottom = interpolate(
|
||||
base[x0][y1],
|
||||
base[x1][y1],
|
||||
horizintalBlend
|
||||
);
|
||||
|
||||
// blend top and bottom interpolation to get the final blend value for this cell
|
||||
perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend);
|
||||
perlinNoiseLayer[x][y] =
|
||||
interpolate(top, bottom, verticalBlend);
|
||||
}
|
||||
}
|
||||
|
||||
@ -143,7 +163,8 @@ public class PerlinNoise {
|
||||
System.out.println("Charset (String): ");
|
||||
charset = in.next();
|
||||
|
||||
perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed);
|
||||
perlinNoise =
|
||||
generatePerlinNoise(width, height, octaveCount, persistence, seed);
|
||||
final char[] chars = charset.toCharArray();
|
||||
final int length = chars.length;
|
||||
final float step = 1f / length;
|
||||
|
@ -141,7 +141,9 @@ public class QueueUsingTwoStacks {
|
||||
System.out.println(myQueue.isEmpty()); // Will print false
|
||||
|
||||
System.out.println(myQueue.remove()); // Will print 1
|
||||
System.out.println((myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL
|
||||
System.out.println(
|
||||
(myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()
|
||||
); // Will print NULL
|
||||
// instack: []
|
||||
// outStack: [(top) 2, 3, 4]
|
||||
|
||||
|
@ -13,7 +13,6 @@ public class RabinKarp {
|
||||
public static final int d = 256;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
scanner = new Scanner(System.in);
|
||||
System.out.println("Enter String");
|
||||
String text = scanner.nextLine();
|
||||
@ -25,7 +24,6 @@ public class RabinKarp {
|
||||
}
|
||||
|
||||
private static void searchPat(String text, String pattern, int q) {
|
||||
|
||||
int m = pattern.length();
|
||||
int n = text.length();
|
||||
int t = 0;
|
||||
@ -45,7 +43,6 @@ public class RabinKarp {
|
||||
}
|
||||
|
||||
for (i = 0; i <= n - m; i++) {
|
||||
|
||||
// if the calculated hash value of the pattern and text matches then
|
||||
// all the characters of the pattern is matched with the text of length equal to length of the
|
||||
// pattern
|
||||
@ -54,10 +51,8 @@ public class RabinKarp {
|
||||
// of the next character after the end
|
||||
// of the evaluated characters is added
|
||||
if (p == t) {
|
||||
|
||||
// if hash value matches then the individual characters are matched
|
||||
for (j = 0; j < m; j++) {
|
||||
|
||||
// if not matched then break out of the loop
|
||||
if (text.charAt(i + j) != pattern.charAt(j)) {
|
||||
break;
|
||||
|
@ -9,11 +9,15 @@ import java.io.InputStreamReader;
|
||||
public class RemoveDuplicateFromString {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(System.in)
|
||||
);
|
||||
String inpStr = br.readLine();
|
||||
|
||||
System.out.println("Actual string is: " + inpStr);
|
||||
System.out.println("String after removing duplicates: " + removeDuplicate(inpStr));
|
||||
System.out.println(
|
||||
"String after removing duplicates: " + removeDuplicate(inpStr)
|
||||
);
|
||||
|
||||
br.close();
|
||||
}
|
||||
|
@ -22,30 +22,23 @@ public class ReturnSubsequence {
|
||||
* @return subsequence
|
||||
*/
|
||||
private static String[] returnSubsequence(String givenString) {
|
||||
if (givenString.length()
|
||||
== 0) // If string is empty we will create an array of size=1 and insert "" (Empty string)
|
||||
// in it
|
||||
{
|
||||
if (
|
||||
givenString.length() == 0
|
||||
) { // in it // If string is empty we will create an array of size=1 and insert "" (Empty string)
|
||||
String[] ans = new String[1];
|
||||
ans[0] = "";
|
||||
return ans;
|
||||
}
|
||||
String[] SmallAns
|
||||
= returnSubsequence(
|
||||
givenString.substring(
|
||||
1)); // recursive call to get subsequences of substring starting from index
|
||||
String[] SmallAns = returnSubsequence(givenString.substring(1)); // recursive call to get subsequences of substring starting from index
|
||||
// position=1
|
||||
|
||||
String[] ans
|
||||
= new String[2 * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns
|
||||
String[] ans = new String[2 * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns
|
||||
int i = 0;
|
||||
for (; i < SmallAns.length; i++) {
|
||||
ans[i] = SmallAns[i]; // Copying all the strings present in SmallAns to ans string array
|
||||
}
|
||||
for (int k = 0; k < SmallAns.length; k++) {
|
||||
ans[k + SmallAns.length]
|
||||
= givenString.charAt(0)
|
||||
+ SmallAns[k]; // Insert character at index=0 of the given substring in front of every string
|
||||
ans[k + SmallAns.length] = givenString.charAt(0) + SmallAns[k]; // Insert character at index=0 of the given substring in front of every string
|
||||
// in SmallAns
|
||||
}
|
||||
return ans;
|
||||
|
@ -33,8 +33,7 @@ public class ReverseStackUsingRecursion {
|
||||
|
||||
// Function Used to reverse Stack Using Recursion
|
||||
private static void reverseUsingRecursion(Stack<Integer> stack) {
|
||||
if (stack.isEmpty()) // If stack is empty then return
|
||||
{
|
||||
if (stack.isEmpty()) { // If stack is empty then return
|
||||
return;
|
||||
}
|
||||
/* All items are stored in call stack until we reach the end*/
|
||||
|
@ -53,7 +53,9 @@ class Schedule {
|
||||
|
||||
System.out.print("Enter the no. of processes: ");
|
||||
noOfProcess = in.nextInt();
|
||||
System.out.println("Enter the arrival, burst and priority of processes");
|
||||
System.out.println(
|
||||
"Enter the arrival, burst and priority of processes"
|
||||
);
|
||||
for (int i = 0; i < noOfProcess; i++) {
|
||||
Process p = new Process();
|
||||
p.pid = i;
|
||||
@ -75,14 +77,14 @@ class Schedule {
|
||||
}
|
||||
|
||||
void startScheduling() {
|
||||
|
||||
processes.sort(
|
||||
new Comparator<Process>() {
|
||||
@Override
|
||||
public int compare(Process a, Process b) {
|
||||
return a.arrivalTime - b.arrivalTime;
|
||||
new Comparator<Process>() {
|
||||
@Override
|
||||
public int compare(Process a, Process b) {
|
||||
return a.arrivalTime - b.arrivalTime;
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
while (!(arrivals.size() == 0 && remainingProcess.size() == 0)) {
|
||||
removeFinishedProcess();
|
||||
@ -92,19 +94,23 @@ class Schedule {
|
||||
}
|
||||
|
||||
remainingProcess.sort(
|
||||
new Comparator<Process>() {
|
||||
private int alpha = 6;
|
||||
private int beta = 1;
|
||||
new Comparator<Process>() {
|
||||
private int alpha = 6;
|
||||
private int beta = 1;
|
||||
|
||||
@Override
|
||||
public int compare(Process a, Process b) {
|
||||
int aRem = a.remainingTime;
|
||||
int bRem = b.remainingTime;
|
||||
int aprior = a.priority;
|
||||
int bprior = b.priority;
|
||||
return (alpha * aRem + beta * aprior) - (alpha * bRem + beta * bprior);
|
||||
@Override
|
||||
public int compare(Process a, Process b) {
|
||||
int aRem = a.remainingTime;
|
||||
int bRem = b.remainingTime;
|
||||
int aprior = a.priority;
|
||||
int bprior = b.priority;
|
||||
return (
|
||||
(alpha * aRem + beta * aprior) -
|
||||
(alpha * bRem + beta * bprior)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
int k = timeElapsed(timer);
|
||||
ageing(k);
|
||||
@ -124,7 +130,8 @@ class Schedule {
|
||||
|
||||
for (int i = 0; i < completed.size(); i++) {
|
||||
int pid = remainingProcess.get(completed.get(i)).pid;
|
||||
processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime;
|
||||
processes.get(pid).waitTime =
|
||||
remainingProcess.get(completed.get(i)).waitTime;
|
||||
remainingProcess.remove(remainingProcess.get(completed.get(i)));
|
||||
}
|
||||
}
|
||||
@ -158,21 +165,25 @@ class Schedule {
|
||||
float tatTime = 0;
|
||||
|
||||
for (int i = 0; i < noOfProcess; i++) {
|
||||
processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime;
|
||||
processes.get(i).turnAroundTime =
|
||||
processes.get(i).waitTime + processes.get(i).burstTime;
|
||||
|
||||
waitTimeTot += processes.get(i).waitTime;
|
||||
tatTime += processes.get(i).turnAroundTime;
|
||||
|
||||
System.out.println(
|
||||
"Process no.: "
|
||||
+ i
|
||||
+ " Wait time: "
|
||||
+ processes.get(i).waitTime
|
||||
+ " Turn Around Time: "
|
||||
+ processes.get(i).turnAroundTime);
|
||||
"Process no.: " +
|
||||
i +
|
||||
" Wait time: " +
|
||||
processes.get(i).waitTime +
|
||||
" Turn Around Time: " +
|
||||
processes.get(i).turnAroundTime
|
||||
);
|
||||
}
|
||||
|
||||
System.out.println("Average Waiting Time: " + waitTimeTot / noOfProcess);
|
||||
System.out.println(
|
||||
"Average Waiting Time: " + waitTimeTot / noOfProcess
|
||||
);
|
||||
System.out.println("Average TAT Time: " + tatTime / noOfProcess);
|
||||
System.out.println("Throughput: " + (float) noOfProcess / (timer - 1));
|
||||
}
|
||||
|
@ -52,9 +52,10 @@ public class SieveOfEratosthenes {
|
||||
}
|
||||
|
||||
//Write all primes to result array
|
||||
int primesCount = (int) Arrays.stream(numbers)
|
||||
.filter(element -> element == Type.PRIME)
|
||||
.count();
|
||||
int primesCount = (int) Arrays
|
||||
.stream(numbers)
|
||||
.filter(element -> element == Type.PRIME)
|
||||
.count();
|
||||
int[] primes = new int[primesCount];
|
||||
|
||||
int primeIndex = 0;
|
||||
@ -68,7 +69,8 @@ public class SieveOfEratosthenes {
|
||||
}
|
||||
|
||||
private enum Type {
|
||||
PRIME, NOT_PRIME
|
||||
PRIME,
|
||||
NOT_PRIME,
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -18,7 +18,11 @@ public class SkylineProblem {
|
||||
for (int i = 0; i < num; i++) {
|
||||
String input = sc.next();
|
||||
String[] data = input.split(",");
|
||||
this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2]));
|
||||
this.add(
|
||||
Integer.parseInt(data[0]),
|
||||
Integer.parseInt(data[1]),
|
||||
Integer.parseInt(data[2])
|
||||
);
|
||||
}
|
||||
this.print(this.findSkyline(0, num - 1));
|
||||
|
||||
@ -58,7 +62,10 @@ public class SkylineProblem {
|
||||
return this.mergeSkyline(sky1, sky2);
|
||||
}
|
||||
|
||||
public ArrayList<Skyline> mergeSkyline(ArrayList<Skyline> sky1, ArrayList<Skyline> sky2) {
|
||||
public ArrayList<Skyline> mergeSkyline(
|
||||
ArrayList<Skyline> sky1,
|
||||
ArrayList<Skyline> sky2
|
||||
) {
|
||||
int currentH1 = 0, currentH2 = 0;
|
||||
ArrayList<Skyline> skyline = new ArrayList<>();
|
||||
int maxH = 0;
|
||||
|
@ -33,7 +33,6 @@ public class StackPostfixNotation {
|
||||
} else {
|
||||
s.push(num1 / num2);
|
||||
}
|
||||
|
||||
// "+", "-", "*", "/"
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,6 @@ public class StringMatchFiniteAutomata {
|
||||
public static Scanner scanner = null;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
scanner = new Scanner(System.in);
|
||||
System.out.println("Enter String");
|
||||
String text = scanner.nextLine();
|
||||
@ -26,7 +25,6 @@ public class StringMatchFiniteAutomata {
|
||||
}
|
||||
|
||||
public static void searchPat(String text, String pat) {
|
||||
|
||||
int m = pat.length();
|
||||
int n = text.length();
|
||||
|
||||
@ -46,7 +44,6 @@ public class StringMatchFiniteAutomata {
|
||||
|
||||
// Computes finite automata for the partern
|
||||
public static void computeFA(String pat, int m, int[][] FA) {
|
||||
|
||||
for (int state = 0; state <= m; ++state) {
|
||||
for (int x = 0; x < CHARS; ++x) {
|
||||
FA[state][x] = getNextState(pat, m, state, x);
|
||||
@ -55,7 +52,6 @@ public class StringMatchFiniteAutomata {
|
||||
}
|
||||
|
||||
public static int getNextState(String pat, int m, int state, int x) {
|
||||
|
||||
// if current state is less than length of pattern
|
||||
// and input character of pattern matches the character in the alphabet
|
||||
// then automata goes to next state
|
||||
@ -64,11 +60,8 @@ public class StringMatchFiniteAutomata {
|
||||
}
|
||||
|
||||
for (int ns = state; ns > 0; ns--) {
|
||||
|
||||
if (pat.charAt(ns - 1) == x) {
|
||||
|
||||
for (int i = 0; i < ns - 1; i++) {
|
||||
|
||||
if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) {
|
||||
break;
|
||||
}
|
||||
|
@ -2,12 +2,9 @@ package com.thealgorithms.others;
|
||||
|
||||
class Sudoku {
|
||||
|
||||
public static boolean isSafe(int[][] board,
|
||||
int row, int col,
|
||||
int num) {
|
||||
public static boolean isSafe(int[][] board, int row, int col, int num) {
|
||||
// Row has the unique (row-clash)
|
||||
for (int d = 0; d < board.length; d++) {
|
||||
|
||||
// Check if the number we are trying to
|
||||
// place is already present in
|
||||
// that row, return false;
|
||||
@ -18,7 +15,6 @@ class Sudoku {
|
||||
|
||||
// Column has the unique numbers (column-clash)
|
||||
for (int r = 0; r < board.length; r++) {
|
||||
|
||||
// Check if the number
|
||||
// we are trying to
|
||||
// place is already present in
|
||||
@ -34,10 +30,8 @@ class Sudoku {
|
||||
int boxRowStart = row - row % sqrt;
|
||||
int boxColStart = col - col % sqrt;
|
||||
|
||||
for (int r = boxRowStart;
|
||||
r < boxRowStart + sqrt; r++) {
|
||||
for (int d = boxColStart;
|
||||
d < boxColStart + sqrt; d++) {
|
||||
for (int r = boxRowStart; r < boxRowStart + sqrt; r++) {
|
||||
for (int d = boxColStart; d < boxColStart + sqrt; d++) {
|
||||
if (board[r][d] == num) {
|
||||
return false;
|
||||
}
|
||||
@ -48,8 +42,7 @@ class Sudoku {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean solveSudoku(
|
||||
int[][] board, int n) {
|
||||
public static boolean solveSudoku(int[][] board, int n) {
|
||||
int row = -1;
|
||||
int col = -1;
|
||||
boolean isEmpty = true;
|
||||
@ -91,9 +84,7 @@ class Sudoku {
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void print(
|
||||
int[][] board, int N) {
|
||||
|
||||
public static void print(int[][] board, int N) {
|
||||
// We got the answer, just print it
|
||||
for (int r = 0; r < N; r++) {
|
||||
for (int d = 0; d < N; d++) {
|
||||
@ -110,17 +101,16 @@ class Sudoku {
|
||||
|
||||
// Driver Code
|
||||
public static void main(String args[]) {
|
||||
|
||||
int[][] board = new int[][]{
|
||||
{3, 0, 6, 5, 0, 8, 4, 0, 0},
|
||||
{5, 2, 0, 0, 0, 0, 0, 0, 0},
|
||||
{0, 8, 7, 0, 0, 0, 0, 3, 1},
|
||||
{0, 0, 3, 0, 1, 0, 0, 8, 0},
|
||||
{9, 0, 0, 8, 6, 3, 0, 0, 5},
|
||||
{0, 5, 0, 0, 9, 0, 6, 0, 0},
|
||||
{1, 3, 0, 0, 0, 0, 2, 5, 0},
|
||||
{0, 0, 0, 0, 0, 0, 0, 7, 4},
|
||||
{0, 0, 5, 2, 0, 6, 3, 0, 0}
|
||||
int[][] board = new int[][] {
|
||||
{ 3, 0, 6, 5, 0, 8, 4, 0, 0 },
|
||||
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
|
||||
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
|
||||
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
|
||||
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
|
||||
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
|
||||
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
|
||||
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 },
|
||||
};
|
||||
int N = board.length;
|
||||
|
||||
|
@ -33,7 +33,6 @@ class ThreeSum {
|
||||
Arrays.sort(a); // Sort the array if array is not sorted
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
|
||||
int l = i + 1, r = n - 1;
|
||||
|
||||
while (l < r) {
|
||||
|
@ -20,7 +20,6 @@ public class TopKWords {
|
||||
FileInputStream fis = null;
|
||||
|
||||
try {
|
||||
|
||||
fis = new FileInputStream(fileName); // open the file
|
||||
int in = 0;
|
||||
String s = ""; // init a empty word
|
||||
@ -65,11 +64,12 @@ public class TopKWords {
|
||||
public static void main(String[] args) {
|
||||
// you can replace the filePath with yours
|
||||
CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt");
|
||||
Map<String, Integer> dictionary
|
||||
= cw.getDictionary(); // get the words dictionary: {word: frequency}
|
||||
Map<String, Integer> dictionary = cw.getDictionary(); // get the words dictionary: {word: frequency}
|
||||
|
||||
// we change the map to list for convenient sort
|
||||
List<Map.Entry<String, Integer>> list = new ArrayList<>(dictionary.entrySet());
|
||||
List<Map.Entry<String, Integer>> list = new ArrayList<>(
|
||||
dictionary.entrySet()
|
||||
);
|
||||
|
||||
// sort by lambda valueComparator
|
||||
list.sort(Comparator.comparing(m -> m.getValue()));
|
||||
|
@ -4,7 +4,12 @@ import java.util.Scanner;
|
||||
|
||||
class TowerOfHanoi {
|
||||
|
||||
public static void shift(int n, String startPole, String intermediatePole, String endPole) {
|
||||
public static void shift(
|
||||
int n,
|
||||
String startPole,
|
||||
String intermediatePole,
|
||||
String endPole
|
||||
) {
|
||||
// if n becomes zero the program returns thus ending the loop.
|
||||
if (n != 0) {
|
||||
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the
|
||||
|
@ -12,12 +12,12 @@ import java.util.Arrays;
|
||||
class TwoPointers {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {10, 20, 35, 50, 75, 80};
|
||||
int[] arr = { 10, 20, 35, 50, 75, 80 };
|
||||
int key = 70;
|
||||
assert isPairedSum(arr, key);
|
||||
/* 20 + 60 == 70 */
|
||||
|
||||
arr = new int[]{1, 2, 3, 4, 5, 6, 7};
|
||||
arr = new int[] { 1, 2, 3, 4, 5, 6, 7 };
|
||||
key = 13;
|
||||
assert isPairedSum(arr, key);
|
||||
/* 6 + 7 == 13 */
|
||||
|
@ -35,23 +35,34 @@ public class Verhoeff {
|
||||
* Dihedral group</a>
|
||||
*/
|
||||
private static final byte[][] MULTIPLICATION_TABLE = {
|
||||
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
|
||||
{1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
|
||||
{2, 3, 4, 0, 1, 7, 8, 9, 5, 6},
|
||||
{3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
|
||||
{4, 0, 1, 2, 3, 9, 5, 6, 7, 8},
|
||||
{5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
|
||||
{6, 5, 9, 8, 7, 1, 0, 4, 3, 2},
|
||||
{7, 6, 5, 9, 8, 2, 1, 0, 4, 3},
|
||||
{8, 7, 6, 5, 9, 3, 2, 1, 0, 4},
|
||||
{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
|
||||
{ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 },
|
||||
{ 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 },
|
||||
{ 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 },
|
||||
{ 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 },
|
||||
{ 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 },
|
||||
{ 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 },
|
||||
{ 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 },
|
||||
{ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 },
|
||||
{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 },
|
||||
};
|
||||
|
||||
/**
|
||||
* The inverse table {@code inv}. Represents the multiplicative inverse of a
|
||||
* digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}.
|
||||
*/
|
||||
private static final byte[] MULTIPLICATIVE_INVERSE = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};
|
||||
private static final byte[] MULTIPLICATIVE_INVERSE = {
|
||||
0,
|
||||
4,
|
||||
3,
|
||||
2,
|
||||
1,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
};
|
||||
|
||||
/**
|
||||
* The permutation table {@code p}. Applies a permutation to each digit
|
||||
@ -60,14 +71,14 @@ public class Verhoeff {
|
||||
* {@code p(i+j,n) = p(i, p(j,n))}.
|
||||
*/
|
||||
private static final byte[][] PERMUTATION_TABLE = {
|
||||
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
|
||||
{1, 5, 7, 6, 2, 8, 3, 0, 9, 4},
|
||||
{5, 8, 0, 3, 7, 9, 6, 1, 4, 2},
|
||||
{8, 9, 1, 6, 0, 4, 3, 5, 2, 7},
|
||||
{9, 4, 5, 3, 1, 2, 6, 8, 7, 0},
|
||||
{4, 2, 8, 6, 5, 7, 3, 9, 0, 1},
|
||||
{2, 7, 9, 3, 8, 0, 6, 4, 1, 5},
|
||||
{7, 0, 4, 6, 9, 1, 3, 2, 5, 8}
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
|
||||
{ 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 },
|
||||
{ 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 },
|
||||
{ 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 },
|
||||
{ 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 },
|
||||
{ 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 },
|
||||
{ 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 },
|
||||
{ 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 },
|
||||
};
|
||||
|
||||
/**
|
||||
@ -137,26 +148,32 @@ public class Verhoeff {
|
||||
|
||||
private static void checkAndPrint(String input) {
|
||||
String validationResult = Verhoeff.verhoeffCheck(input)
|
||||
? "valid"
|
||||
: "not valid";
|
||||
? "valid"
|
||||
: "not valid";
|
||||
System.out.println("Input '" + input + "' is " + validationResult);
|
||||
}
|
||||
|
||||
private static void generateAndPrint(String input) {
|
||||
String result = addVerhoeffChecksum(input);
|
||||
System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'");
|
||||
System.out.println(
|
||||
"Generate and add checksum to initial value '" +
|
||||
input +
|
||||
"'. Result: '" +
|
||||
result +
|
||||
"'"
|
||||
);
|
||||
}
|
||||
|
||||
private static void checkInput(String input) {
|
||||
Objects.requireNonNull(input);
|
||||
if (!input.matches("\\d+")) {
|
||||
throw new IllegalArgumentException("Input '" + input + "' contains not only digits");
|
||||
throw new IllegalArgumentException(
|
||||
"Input '" + input + "' contains not only digits"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static int[] toIntArray(String string) {
|
||||
return string.chars()
|
||||
.map(i -> Character.digit(i, 10))
|
||||
.toArray();
|
||||
return string.chars().map(i -> Character.digit(i, 10)).toArray();
|
||||
}
|
||||
}
|
||||
|
@ -5,12 +5,14 @@ import java.util.List;
|
||||
|
||||
public class HammingDistance {
|
||||
|
||||
|
||||
|
||||
public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) {
|
||||
|
||||
if(senderBits.length() != receiverBits.length()) {
|
||||
throw new IllegalArgumentException("Sender and Receiver bits should be same");
|
||||
public int getHammingDistanceBetweenBits(
|
||||
String senderBits,
|
||||
String receiverBits
|
||||
) {
|
||||
if (senderBits.length() != receiverBits.length()) {
|
||||
throw new IllegalArgumentException(
|
||||
"Sender and Receiver bits should be same"
|
||||
);
|
||||
}
|
||||
|
||||
List<byte[]> byteArray = new ArrayList<>();
|
||||
@ -18,20 +20,19 @@ public class HammingDistance {
|
||||
byteArray.add(senderBits.getBytes());
|
||||
byteArray.add(receiverBits.getBytes());
|
||||
|
||||
|
||||
byte[] senderData = byteArray.get(0);
|
||||
byte[] receiverData = byteArray.get(1);
|
||||
|
||||
int totalErrorBitCount = 0;
|
||||
|
||||
for(int i = 0; i < senderData.length; i++){
|
||||
totalErrorBitCount += senderData[i] ^ receiverData[i];
|
||||
for (int i = 0; i < senderData.length; i++) {
|
||||
totalErrorBitCount += senderData[i] ^ receiverData[i];
|
||||
}
|
||||
|
||||
if(totalErrorBitCount == 0){
|
||||
if (totalErrorBitCount == 0) {
|
||||
System.out.println("No Error bit in data segments");
|
||||
} else{
|
||||
System.out.println("Total Error bit count "+totalErrorBitCount);
|
||||
} else {
|
||||
System.out.println("Total Error bit count " + totalErrorBitCount);
|
||||
}
|
||||
return totalErrorBitCount;
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.thealgorithms.others;
|
||||
|
||||
public class countSetBits {
|
||||
|
||||
/**
|
||||
* The below algorithm is called as Brian Kernighan's algorithm
|
||||
* We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. The idea is to only consider the set bits of an integer by turning off its rightmost set bit (after counting it), so the next iteration of the loop considers the next rightmost bit.
|
||||
@ -35,12 +36,12 @@ public class countSetBits {
|
||||
* @param num takes Long number whose number of set bit is to be found
|
||||
* @return the count of set bits in the binary equivalent
|
||||
*/
|
||||
public long countsetBits(long num){
|
||||
long cnt=0;
|
||||
while(num>0){
|
||||
public long countsetBits(long num) {
|
||||
long cnt = 0;
|
||||
while (num > 0) {
|
||||
cnt++;
|
||||
num&=(num-1);
|
||||
num &= (num - 1);
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user