mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-24 04:54:21 +08:00
@ -66,8 +66,7 @@ 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);
|
||||
}
|
||||
|
@ -25,13 +25,8 @@ 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];
|
||||
@ -54,23 +49,11 @@ 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];
|
||||
|
||||
@ -113,16 +96,12 @@ public class BankersAlgorithm {
|
||||
|
||||
// If we could not find a next process in safe sequence.
|
||||
if (!foundSafeSystem) {
|
||||
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] + " ");
|
||||
}
|
||||
@ -163,9 +142,7 @@ 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();
|
||||
}
|
||||
}
|
||||
@ -181,20 +158,14 @@ public class BankersAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
checkSafeSystem(
|
||||
processes,
|
||||
availableArray,
|
||||
maxArray,
|
||||
allocationArray,
|
||||
numberOfProcesses,
|
||||
numberOfResources
|
||||
);
|
||||
checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses,
|
||||
numberOfResources);
|
||||
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
/*
|
||||
Example:
|
||||
Example:
|
||||
n = 5
|
||||
m = 3
|
||||
|
||||
@ -202,10 +173,10 @@ public class BankersAlgorithm {
|
||||
0 1 2 0 1 2 0 1 2
|
||||
|
||||
0 0 1 0 7 5 3 3 3 2
|
||||
1 2 0 0 3 2 2
|
||||
1 2 0 0 3 2 2
|
||||
2 3 0 2 9 0 2
|
||||
3 2 1 1 2 2 2
|
||||
4 0 0 2 4 3 3
|
||||
|
||||
Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2
|
||||
Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2
|
||||
*/
|
||||
|
@ -1,7 +1,8 @@
|
||||
/* this Code is the illustration of Boyer moore's voting algorithm to
|
||||
find the majority element is an array that appears more than n/2 times in an array
|
||||
where "n" is the length of the array.
|
||||
For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
|
||||
For more information on the algorithm refer
|
||||
https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
|
||||
*/
|
||||
package com.thealgorithms.others;
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.thealgorithms.others;
|
||||
|
||||
/**
|
||||
* Generates a crc16 checksum for a given string
|
||||
* Generates a crc16 checksum for a given string
|
||||
*/
|
||||
public class CRC16 {
|
||||
|
||||
@ -9,21 +9,20 @@ public class CRC16 {
|
||||
System.out.println(crc16("Hello World!"));
|
||||
}
|
||||
|
||||
public static String crc16(String message) {
|
||||
int crc = 0xFFFF; // initial value
|
||||
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
|
||||
byte[] bytes = message.getBytes();
|
||||
public static String crc16(String message) {
|
||||
int crc = 0xFFFF; // initial value
|
||||
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
|
||||
byte[] bytes = message.getBytes();
|
||||
|
||||
for (byte b : bytes) {
|
||||
for (int i = 0; i < 8; i++) {
|
||||
boolean bit = ((b >> (7 - i) & 1) == 1);
|
||||
boolean c15 = ((crc >> 15 & 1) == 1);
|
||||
crc <<= 1;
|
||||
if (c15 ^ bit)
|
||||
crc ^= polynomial;
|
||||
}
|
||||
}
|
||||
crc &= 0xffff;
|
||||
return Integer.toHexString(crc).toUpperCase();
|
||||
}
|
||||
for (byte b : bytes) {
|
||||
for (int i = 0; i < 8; i++) {
|
||||
boolean bit = ((b >> (7 - i) & 1) == 1);
|
||||
boolean c15 = ((crc >> 15 & 1) == 1);
|
||||
crc <<= 1;
|
||||
if (c15 ^ bit) crc ^= polynomial;
|
||||
}
|
||||
}
|
||||
crc &= 0xffff;
|
||||
return Integer.toHexString(crc).toUpperCase();
|
||||
}
|
||||
}
|
||||
|
@ -6,27 +6,24 @@ public class Conway {
|
||||
|
||||
/*
|
||||
* This class will generate the conway sequence also known as the look and say sequence.
|
||||
* To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example:
|
||||
*1 is read off as "one 1" or 11.
|
||||
*11 is read off as "two 1s" or 21.
|
||||
*21 is read off as "one 2, one 1" or 1211.
|
||||
*1211 is read off as "one 1, one 2, two 1s" or 111221.
|
||||
*111221 is read off as "three 1s, two 2s, one 1" or 312211.
|
||||
* https://en.wikipedia.org/wiki/Look-and-say_sequence
|
||||
* To generate a member of the sequence from the previous member, read off the digits of the
|
||||
*previous member, counting the number of digits in groups of the same digit. For example: 1 is
|
||||
*read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, one 1"
|
||||
*or 1211. 1211 is read off as "one 1, one 2, two 1s" or 111221. 111221 is read off as "three
|
||||
*1s, two 2s, one 1" or 312211. https://en.wikipedia.org/wiki/Look-and-say_sequence
|
||||
* */
|
||||
|
||||
private static final StringBuilder builder = new StringBuilder();
|
||||
|
||||
protected static List<String> generateList(String originalString, int maxIteration) {
|
||||
List<String> numbers = new ArrayList<>();
|
||||
for(int i=0; i<maxIteration; i++) {
|
||||
for (int i = 0; i < maxIteration; i++) {
|
||||
originalString = generateNextElement(originalString);
|
||||
numbers.add(originalString);
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
|
||||
public static String generateNextElement(String originalString) {
|
||||
builder.setLength(0);
|
||||
String[] stp = originalString.split("(?<=(.))(?!\\1)");
|
||||
|
@ -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},
|
||||
};
|
||||
|
||||
/**
|
||||
@ -99,20 +99,13 @@ public class Damm {
|
||||
private static void generateAndPrint(String input) {
|
||||
String result = addDammChecksum(input);
|
||||
System.out.println(
|
||||
"Generate and add checksum to initial value '" +
|
||||
input +
|
||||
"'. Result: '" +
|
||||
result +
|
||||
"'"
|
||||
);
|
||||
"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");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -119,19 +119,14 @@ 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;
|
||||
}
|
||||
return neighbours != null ? neighbours.equals(vertex.neighbours) : vertex.neighbours == null;
|
||||
return neighbours != null ? neighbours.equals(vertex.neighbours)
|
||||
: vertex.neighbours == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -140,8 +135,7 @@ 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;
|
||||
}
|
||||
|
||||
@ -170,8 +164,8 @@ class Graph {
|
||||
// another pass to set neighbouring vertices
|
||||
for (Edge e : edges) {
|
||||
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
|
||||
// graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected
|
||||
// graph
|
||||
// graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an
|
||||
// undirected graph
|
||||
}
|
||||
}
|
||||
|
||||
@ -180,10 +174,7 @@ 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);
|
||||
@ -208,7 +199,8 @@ class Graph {
|
||||
// vertex with shortest distance (first iteration will return source)
|
||||
u = q.pollFirst();
|
||||
if (u.dist == Integer.MAX_VALUE) {
|
||||
break; // we can ignore u (and any other remaining vertices) since they are unreachable
|
||||
break; // we can ignore u (and any other remaining vertices) since they are
|
||||
// unreachable
|
||||
}
|
||||
// look at distances to each neighbour
|
||||
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
|
||||
@ -230,10 +222,7 @@ 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;
|
||||
}
|
||||
|
||||
|
@ -6,9 +6,7 @@ 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++) {
|
||||
|
@ -7,9 +7,8 @@ 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);
|
||||
|
@ -35,11 +35,7 @@ public class Huffman {
|
||||
// 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)
|
||||
) {
|
||||
if (root.left == null && root.right == null && Character.isLetter(root.c)) {
|
||||
// c is the character in the node
|
||||
System.out.println(root.c + ":" + s);
|
||||
|
||||
@ -60,15 +56,12 @@ public class Huffman {
|
||||
|
||||
// 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()
|
||||
);
|
||||
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator());
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
// creating a Huffman node object
|
||||
|
@ -160,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,9 +18,7 @@ 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();
|
||||
|
@ -56,8 +56,7 @@ 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 {
|
||||
@ -77,10 +76,7 @@ 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);
|
||||
@ -98,18 +94,14 @@ 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);
|
||||
@ -130,23 +122,15 @@ 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)));
|
||||
}
|
||||
|
||||
@ -163,15 +147,9 @@ 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
|
||||
|
@ -13,31 +13,33 @@ import java.util.Comparator;
|
||||
*/
|
||||
public class LineSweep {
|
||||
|
||||
/** Find Maximum end point
|
||||
/**
|
||||
* Find Maximum end point
|
||||
* param = ranges : Array of range[start,end]
|
||||
* return Maximum Endpoint
|
||||
*/
|
||||
public static int FindMaximumEndPoint (int[][]ranges){
|
||||
Arrays.sort(ranges, Comparator.comparingInt(a->a[1]));
|
||||
return ranges[ranges.length-1][1];
|
||||
}
|
||||
public static int FindMaximumEndPoint(int[][] ranges) {
|
||||
Arrays.sort(ranges, Comparator.comparingInt(a -> a[1]));
|
||||
return ranges[ranges.length - 1][1];
|
||||
}
|
||||
|
||||
/** Find if any ranges overlap
|
||||
/**
|
||||
* Find if any ranges overlap
|
||||
* param = ranges : Array of range[start,end]
|
||||
* return true if overlap exists false otherwise.
|
||||
*/
|
||||
public static boolean isOverlap(int[][] ranges) {
|
||||
|
||||
int maximumEndPoint = FindMaximumEndPoint(ranges);
|
||||
Arrays.sort(ranges, Comparator.comparingInt(a->a[0]));
|
||||
int[] numberLine = new int[maximumEndPoint+2];
|
||||
Arrays.sort(ranges, Comparator.comparingInt(a -> a[0]));
|
||||
int[] numberLine = new int[maximumEndPoint + 2];
|
||||
for (int[] range : ranges) {
|
||||
|
||||
int start = range[0];
|
||||
int end = range[1];
|
||||
|
||||
numberLine[start] += 1;
|
||||
numberLine[end+1] -= 1;
|
||||
numberLine[end + 1] -= 1;
|
||||
}
|
||||
|
||||
int current = 0;
|
||||
@ -46,6 +48,6 @@ public class LineSweep {
|
||||
current += num;
|
||||
overlaps = Math.max(overlaps, current);
|
||||
}
|
||||
return overlaps >1 ;
|
||||
return overlaps > 1;
|
||||
}
|
||||
}
|
||||
|
@ -21,11 +21,7 @@ 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);
|
||||
}
|
||||
|
||||
@ -40,11 +36,7 @@ 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;
|
||||
@ -66,11 +58,8 @@ 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());
|
||||
}
|
||||
|
@ -27,7 +27,8 @@ final public class LowestBasePalindrome {
|
||||
* @param number the input number
|
||||
* @param base the given base
|
||||
* @exception IllegalArgumentException number is negative or base is less than 2
|
||||
* @return the list containing the digits of the input number in the given base, the most significant digit is at the end of the array
|
||||
* @return the list containing the digits of the input number in the given base, the most
|
||||
* significant digit is at the end of the array
|
||||
*/
|
||||
public static ArrayList<Integer> computeDigitsInBase(int number, int base) {
|
||||
checkNumber(number);
|
||||
@ -46,8 +47,8 @@ final public class LowestBasePalindrome {
|
||||
* @return true, if the input array is a palindrome, false otherwise
|
||||
*/
|
||||
public static boolean isPalindromic(ArrayList<Integer> list) {
|
||||
for (int pos = 0; pos < list.size()/2; ++pos) {
|
||||
if(list.get(pos) != list.get(list.size()-1-pos)) {
|
||||
for (int pos = 0; pos < list.size() / 2; ++pos) {
|
||||
if (list.get(pos) != list.get(list.size() - 1 - pos)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -59,7 +60,8 @@ final public class LowestBasePalindrome {
|
||||
* @param number the input number
|
||||
* @param base the given base
|
||||
* @exception IllegalArgumentException number is negative or base is less than 2
|
||||
* @return true, if the input number represented in the given base is a palindrome, false otherwise
|
||||
* @return true, if the input number represented in the given base is a palindrome, false
|
||||
* otherwise
|
||||
*/
|
||||
public static boolean isPalindromicInBase(int number, int base) {
|
||||
checkNumber(number);
|
||||
@ -78,14 +80,15 @@ final public class LowestBasePalindrome {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief finds the smallest base for which the representation of the input number is a palindrome
|
||||
* @brief finds the smallest base for which the representation of the input number is a
|
||||
* palindrome
|
||||
* @param number the input number
|
||||
* @exception IllegalArgumentException number is negative
|
||||
* @return the smallest base for which the representation of the input number is a palindrome
|
||||
*/
|
||||
public static int lowestBasePalindrome(int number) {
|
||||
int base = 2;
|
||||
while(!isPalindromicInBase(number, base)) {
|
||||
while (!isPalindromicInBase(number, base)) {
|
||||
++base;
|
||||
}
|
||||
return base;
|
||||
|
@ -67,8 +67,9 @@ 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);
|
||||
|
||||
@ -83,9 +84,7 @@ 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
|
||||
);
|
||||
System.out.println("Input " + Arrays.toString(input) + " is " + validationResult);
|
||||
}
|
||||
|
||||
/*
|
||||
@ -109,21 +108,15 @@ 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"
|
||||
);
|
||||
"Credit card number {" + cardNumber + "} - have a typo");
|
||||
}
|
||||
|
||||
return new CreditCard(cardNumbers);
|
||||
@ -146,11 +139,7 @@ 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) {
|
||||
@ -161,19 +150,11 @@ public class Luhn {
|
||||
private static void businessExample(String cardNumber) {
|
||||
try {
|
||||
System.out.println(
|
||||
"Trying to create CreditCard object from valid card number: " +
|
||||
cardNumber
|
||||
);
|
||||
"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,23 +27,13 @@ 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);
|
||||
@ -80,63 +70,38 @@ public class Mandelbrot {
|
||||
* @param useDistanceColorCoding Render in color or black and white.
|
||||
* @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
|
||||
) {
|
||||
public static BufferedImage getImage(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()
|
||||
);
|
||||
image.setRGB(imageX, imageY,
|
||||
useDistanceColorCoding ? colorCodedColorMap(distance).getRGB()
|
||||
: blackAndWhiteColorMap(distance).getRGB());
|
||||
}
|
||||
}
|
||||
|
||||
@ -179,18 +144,18 @@ public class Mandelbrot {
|
||||
int t = (int) (val * (1 - (1 - f) * saturation));
|
||||
|
||||
switch (hi) {
|
||||
case 0:
|
||||
return new Color(v, t, p);
|
||||
case 1:
|
||||
return new Color(q, v, p);
|
||||
case 2:
|
||||
return new Color(p, v, t);
|
||||
case 3:
|
||||
return new Color(p, q, v);
|
||||
case 4:
|
||||
return new Color(t, p, v);
|
||||
default:
|
||||
return new Color(v, p, q);
|
||||
case 0:
|
||||
return new Color(v, t, p);
|
||||
case 1:
|
||||
return new Color(q, v, p);
|
||||
case 2:
|
||||
return new Color(p, v, t);
|
||||
case 3:
|
||||
return new Color(p, q, v);
|
||||
case 4:
|
||||
return new Color(t, p, v);
|
||||
default:
|
||||
return new Color(v, p, q);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -205,11 +170,7 @@ 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;
|
||||
|
@ -21,18 +21,16 @@ 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);
|
||||
|
||||
/**
|
||||
* A constant value used to indicate that an allocation has not been made.
|
||||
* This value is used as a sentinel value to represent that no allocation has been made
|
||||
* when allocating space in an array or other data structure.
|
||||
* A constant value used to indicate that an allocation has not been made.
|
||||
* This value is used as a sentinel value to represent that no allocation has been made
|
||||
* when allocating space in an array or other data structure.
|
||||
* The value is -255 and is marked as protected and final to ensure that it cannot be modified
|
||||
* from outside the class and that its value remains consistent throughout the program execution.
|
||||
*
|
||||
* from outside the class and that its value remains consistent throughout the program
|
||||
* execution.
|
||||
*
|
||||
* @author: Ishan Makadia (github.com/intrepid-ishan)
|
||||
* @version: April 06, 2023
|
||||
*/
|
||||
@ -44,7 +42,6 @@ public abstract class MemoryManagementAlgorithms {
|
||||
*/
|
||||
class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
|
||||
|
||||
/**
|
||||
* Method to find the maximum valued element of an array filled with
|
||||
* positive integers.
|
||||
@ -75,13 +72,12 @@ 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;
|
||||
}
|
||||
@ -101,18 +97,19 @@ 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
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the best-fit algorithm
|
||||
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,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
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;
|
||||
@ -136,7 +133,8 @@ 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;
|
||||
@ -161,18 +159,19 @@ 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
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the worst-fit algorithm
|
||||
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,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
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;
|
||||
@ -184,7 +183,6 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
*/
|
||||
class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
|
||||
|
||||
/**
|
||||
* Method to find the index of the memory block that is going to fit the
|
||||
* given process based on the first fit algorithm.
|
||||
@ -216,18 +214,19 @@ 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
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the first-fit algorithm
|
||||
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,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
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;
|
||||
@ -239,12 +238,14 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
*/
|
||||
class NextFit extends MemoryManagementAlgorithms {
|
||||
|
||||
private int counter = 0; // variable that keeps the position of the last registration into the memory
|
||||
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,
|
||||
* if the search is interrupted in between, the new search is carried out from the last location.
|
||||
* if the search is interrupted in between, the new search is carried out from the last
|
||||
* location.
|
||||
*
|
||||
* @param blocks: the array with the available memory blocks.
|
||||
* @param process: the size of the process.
|
||||
@ -278,18 +279,19 @@ 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
|
||||
) {
|
||||
// The array list responsible for saving the memory allocations done by the first-fit algorithm
|
||||
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,
|
||||
sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
|
||||
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,11 +43,7 @@ public class MiniMaxAlgorithm {
|
||||
|
||||
System.out.println(Arrays.toString(miniMaxAlgorith.getScores()));
|
||||
System.out.println(
|
||||
"The best score for " +
|
||||
(isMaximizer ? "Maximizer" : "Minimizer") +
|
||||
" is " +
|
||||
bestScore
|
||||
);
|
||||
"The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -59,12 +55,7 @@ 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.
|
||||
@ -88,13 +79,8 @@ 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.printf(
|
||||
"From %02d and %02d, %s chooses %02d%n",
|
||||
score1,
|
||||
score2,
|
||||
(isMaximizer ? "Maximizer" : "Minimizer"),
|
||||
bestScore
|
||||
);
|
||||
System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2,
|
||||
(isMaximizer ? "Maximizer" : "Minimizer"), bestScore);
|
||||
}
|
||||
|
||||
return bestScore;
|
||||
|
@ -11,8 +11,7 @@ class PageRank {
|
||||
nodes = in.nextInt();
|
||||
PageRank p = new PageRank();
|
||||
System.out.println(
|
||||
"Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "
|
||||
);
|
||||
"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();
|
||||
@ -37,13 +36,8 @@ class PageRank {
|
||||
int k = 1; // For Traversing
|
||||
int ITERATION_STEP = 1;
|
||||
InitialPageRank = 1 / totalNodes;
|
||||
System.out.printf(
|
||||
" Total Number of Nodes :" +
|
||||
totalNodes +
|
||||
"\t Initial PageRank of All Nodes :" +
|
||||
InitialPageRank +
|
||||
"\n"
|
||||
);
|
||||
System.out.printf(" Total Number of Nodes :" + totalNodes
|
||||
+ "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n");
|
||||
|
||||
// 0th ITERATION _ OR _ INITIALIZATION PHASE //
|
||||
for (k = 1; k <= totalNodes; k++) {
|
||||
@ -52,9 +46,7 @@ class PageRank {
|
||||
System.out.print("\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
|
||||
@ -64,21 +56,13 @@ class PageRank {
|
||||
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
|
||||
OutgoingLinks
|
||||
= 0; // Count the Number of Outgoing Links for each ExternalNodeNumber
|
||||
while (k <= totalNodes) {
|
||||
if (this.path[ExternalNodeNumber][k] == 1) {
|
||||
OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links
|
||||
@ -86,21 +70,14 @@ 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;
|
||||
@ -108,16 +85,13 @@ 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.print("\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,11 +38,7 @@ 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,12 +18,7 @@ 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][][];
|
||||
@ -38,8 +33,7 @@ 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;
|
||||
@ -76,12 +70,7 @@ 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
|
||||
@ -101,22 +90,13 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -163,8 +143,7 @@ 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;
|
||||
|
@ -47,7 +47,6 @@ public class PrintAMatrixInSpiralOrder {
|
||||
}
|
||||
|
||||
row--;
|
||||
|
||||
}
|
||||
|
||||
// print columns from first except printed elements
|
||||
@ -57,9 +56,7 @@ public class PrintAMatrixInSpiralOrder {
|
||||
}
|
||||
c++;
|
||||
}
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -142,8 +142,7 @@ public class QueueUsingTwoStacks {
|
||||
|
||||
System.out.println(myQueue.remove()); // Will print 1
|
||||
System.out.println(
|
||||
(myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()
|
||||
); // Will print NULL
|
||||
(myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL
|
||||
// instack: []
|
||||
// outStack: [(top) 2, 3, 4]
|
||||
|
||||
|
@ -35,21 +35,19 @@ public class RabinKarp {
|
||||
h = (int) Math.pow(d, m - 1) % q;
|
||||
|
||||
for (i = 0; i < m; i++) {
|
||||
// hash value is calculated for each character and then added with the hash value of the next
|
||||
// character for pattern
|
||||
// as well as the text for length equal to the length of pattern
|
||||
// hash value is calculated for each character and then added with the hash value of the
|
||||
// next character for pattern as well as the text for length equal to the length of
|
||||
// pattern
|
||||
p = (d * p + pattern.charAt(i)) % q;
|
||||
t = (d * t + text.charAt(i)) % q;
|
||||
}
|
||||
|
||||
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
|
||||
// if all matches then pattern exist in string
|
||||
// if not then the hash value of the first character of the text is subtracted and hash value
|
||||
// of the next character after the end
|
||||
// of the evaluated characters is added
|
||||
// all the characters of the pattern is matched with the text of length equal to length
|
||||
// of the pattern if all matches then pattern exist in string if not then the hash value
|
||||
// of the first character of the text is subtracted and hash value 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++) {
|
||||
@ -65,10 +63,9 @@ public class RabinKarp {
|
||||
}
|
||||
}
|
||||
|
||||
// if i<n-m then hash value of the first character of the text is subtracted and hash value of
|
||||
// the next character after the end
|
||||
// of the evaluated characters is added to get the hash value of the next window of characters
|
||||
// in the text
|
||||
// if i<n-m then hash value of the first character of the text is subtracted and hash
|
||||
// value of the next character after the end of the evaluated characters is added to get
|
||||
// the hash value of the next window of characters in the text
|
||||
if (i < n - m) {
|
||||
t = (d * (t - text.charAt(i) * h) + text.charAt(i + m)) % q;
|
||||
|
||||
|
@ -9,15 +9,11 @@ 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();
|
||||
}
|
||||
|
@ -8,7 +8,8 @@ public class ReturnSubsequence {
|
||||
System.out.println("Enter String: ");
|
||||
Scanner s = new Scanner(System.in);
|
||||
String givenString = s.next(); // given string
|
||||
String[] subsequence = returnSubsequence(givenString); // calling returnSubsequence() function
|
||||
String[] subsequence
|
||||
= returnSubsequence(givenString); // calling returnSubsequence() function
|
||||
System.out.println("Subsequences : ");
|
||||
// print the given array of subsequences
|
||||
for (int i = 0; i < subsequence.length; i++) {
|
||||
@ -22,23 +23,26 @@ public class ReturnSubsequence {
|
||||
* @return subsequence
|
||||
*/
|
||||
private static String[] returnSubsequence(String givenString) {
|
||||
if (
|
||||
givenString.length() == 0
|
||||
) { // in it // If string is empty we will create an array of size=1 and insert "" (Empty string)
|
||||
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;
|
||||
|
@ -30,10 +30,8 @@ public class SieveOfEratosthenes {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
@ -19,10 +19,7 @@ public class SkylineProblem {
|
||||
String input = sc.next();
|
||||
String[] data = input.split(",");
|
||||
this.add(
|
||||
Integer.parseInt(data[0]),
|
||||
Integer.parseInt(data[1]),
|
||||
Integer.parseInt(data[2])
|
||||
);
|
||||
Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2]));
|
||||
}
|
||||
this.print(this.findSkyline(0, num - 1));
|
||||
|
||||
@ -62,10 +59,7 @@ 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;
|
||||
|
@ -102,15 +102,15 @@ 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 },
|
||||
{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;
|
||||
|
||||
|
@ -64,12 +64,11 @@ 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,20 +4,15 @@ 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
|
||||
// intermediatePole
|
||||
// Shift function is called in recursion for swapping the n-1 disc from the startPole to
|
||||
// the intermediatePole
|
||||
shift(n - 1, startPole, endPole, intermediatePole);
|
||||
System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing
|
||||
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole
|
||||
// to the endPole
|
||||
// Shift function is called in recursion for swapping the n-1 disc from the
|
||||
// intermediatePole to the endPole
|
||||
shift(n - 1, intermediatePole, startPole, endPole);
|
||||
}
|
||||
}
|
||||
|
@ -35,16 +35,16 @@ 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},
|
||||
};
|
||||
|
||||
/**
|
||||
@ -71,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},
|
||||
};
|
||||
|
||||
/**
|
||||
@ -147,29 +147,20 @@ public class Verhoeff {
|
||||
}
|
||||
|
||||
private static void checkAndPrint(String input) {
|
||||
String validationResult = Verhoeff.verhoeffCheck(input)
|
||||
? "valid"
|
||||
: "not valid";
|
||||
String validationResult = Verhoeff.verhoeffCheck(input) ? "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 +
|
||||
"'"
|
||||
);
|
||||
"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");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,14 +5,9 @@ import java.util.List;
|
||||
|
||||
public class HammingDistance {
|
||||
|
||||
public int getHammingDistanceBetweenBits(
|
||||
String senderBits,
|
||||
String receiverBits
|
||||
) {
|
||||
public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) {
|
||||
if (senderBits.length() != receiverBits.length()) {
|
||||
throw new IllegalArgumentException(
|
||||
"Sender and Receiver bits should be same"
|
||||
);
|
||||
throw new IllegalArgumentException("Sender and Receiver bits should be same");
|
||||
}
|
||||
|
||||
List<byte[]> byteArray = new ArrayList<>();
|
||||
|
@ -2,37 +2,41 @@ 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.
|
||||
/**
|
||||
* 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.
|
||||
|
||||
The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This works as the expression n-1 flips all the bits after the rightmost set bit of n, including the rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n.
|
||||
The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This
|
||||
works as the expression n-1 flips all the bits after the rightmost set bit of n, including the
|
||||
rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n.
|
||||
|
||||
For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set.
|
||||
|
||||
1st iteration of the loop: n = 52
|
||||
|
||||
|
||||
00110100 & (n)
|
||||
00110011 (n-1)
|
||||
~~~~~~~~
|
||||
00110000
|
||||
|
||||
|
||||
|
||||
|
||||
2nd iteration of the loop: n = 48
|
||||
|
||||
|
||||
00110000 & (n)
|
||||
00101111 (n-1)
|
||||
~~~~~~~~
|
||||
00100000
|
||||
|
||||
|
||||
|
||||
|
||||
3rd iteration of the loop: n = 32
|
||||
|
||||
|
||||
00100000 & (n)
|
||||
00011111 (n-1)
|
||||
~~~~~~~~
|
||||
00000000 (n = 0)
|
||||
|
||||
|
||||
* @param num takes Long number whose number of set bit is to be found
|
||||
* @return the count of set bits in the binary equivalent
|
||||
*/
|
||||
|
Reference in New Issue
Block a user