Skip to content

Commit d1d5246

Browse files
Merge branch 'master' into add-crc32-test
2 parents 5cf0207 + a91cd7b commit d1d5246

12 files changed

Lines changed: 710 additions & 46 deletions

File tree

‎src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java‎

Lines changed: 49 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,18 @@ public String encrypt(String plaintext, String key) {
8080
public String decrypt(String ciphertext, String key) {
8181
String fractionatedText = reverseColumnarTransposition(ciphertext, key);
8282

83+
if (fractionatedText.length() % 2 != 0) {
84+
throw new IllegalArgumentException("Invalid ciphertext: odd number of ADFGVX letters.");
85+
}
86+
8387
StringBuilder plaintext = new StringBuilder();
8488
for (int i = 0; i < fractionatedText.length(); i += 2) {
8589
String pair = fractionatedText.substring(i, i + 2);
86-
plaintext.append(POLYBIUS_MAP.get(pair));
90+
Character letter = POLYBIUS_MAP.get(pair);
91+
if (letter == null) {
92+
throw new IllegalArgumentException("Invalid ciphertext: unknown ADFGVX pair \"" + pair + "\".");
93+
}
94+
plaintext.append(letter);
8795
}
8896

8997
return plaintext.toString();
@@ -110,11 +118,7 @@ private String columnarTransposition(String text, String key) {
110118

111119
// Read columns based on the alphabetical order of the key
112120
StringBuilder ciphertext = new StringBuilder();
113-
char[] sortedKey = key.toCharArray();
114-
Arrays.sort(sortedKey);
115-
116-
for (char keyChar : sortedKey) {
117-
int column = key.indexOf(keyChar);
121+
for (int column : columnsInKeyOrder(key)) {
118122
for (char[] row : table) {
119123
if (row[column] != '_') {
120124
ciphertext.append(row[column]);
@@ -125,6 +129,24 @@ private String columnarTransposition(String text, String key) {
125129
return ciphertext.toString();
126130
}
127131

132+
/**
133+
* Returns the column indices in the order the key imposes: alphabetical by
134+
* key letter, with repeated letters ordered by their first occurrence.
135+
* Using key.indexOf for repeated letters would map both occurrences to the
136+
* same column and make the transposition lossy.
137+
*/
138+
private int[] columnsInKeyOrder(String key) {
139+
Integer[] order = new Integer[key.length()];
140+
for (int i = 0; i < order.length; i++) {
141+
order[i] = i;
142+
}
143+
Arrays.sort(order, (a, b) -> {
144+
int byLetter = Character.compare(key.charAt(a), key.charAt(b));
145+
return byLetter != 0 ? byLetter : Integer.compare(a, b);
146+
});
147+
return Arrays.stream(order).mapToInt(Integer::intValue).toArray();
148+
}
149+
128150
/**
129151
* Helper method: Reverses the columnar transposition during decryption
130152
*
@@ -133,31 +155,36 @@ private String columnarTransposition(String text, String key) {
133155
* @return The reversed text
134156
*/
135157
private String reverseColumnarTransposition(String ciphertext, String key) {
136-
int numRows = (int) Math.ceil((double) ciphertext.length() / key.length());
137-
char[][] table = new char[numRows][key.length()];
158+
int numCols = key.length();
159+
int fullRows = ciphertext.length() / numCols;
160+
int remainder = ciphertext.length() % numCols;
161+
// The last row of the encryption table is only partially filled: the
162+
// first `remainder` columns hold one extra character. The previous
163+
// implementation assumed every column had the same length, which
164+
// misaligned the whole grid whenever the length was not a multiple of
165+
// the key length.
166+
int[] columnLength = new int[numCols];
167+
for (int column = 0; column < numCols; column++) {
168+
columnLength[column] = fullRows + (column < remainder ? 1 : 0);
169+
}
138170

139-
char[] sortedKey = key.toCharArray();
140-
Arrays.sort(sortedKey);
171+
int numRows = fullRows + (remainder > 0 ? 1 : 0);
172+
char[][] table = new char[numRows][numCols];
141173

142174
int index = 0;
143175
// Populate the table column by column according to the sorted key
144-
for (char keyChar : sortedKey) {
145-
int column = key.indexOf(keyChar);
146-
for (int row = 0; row < numRows; row++) {
147-
if (index < ciphertext.length()) {
148-
table[row][column] = ciphertext.charAt(index++);
149-
} else {
150-
table[row][column] = '_';
151-
}
176+
for (int column : columnsInKeyOrder(key)) {
177+
for (int row = 0; row < columnLength[column]; row++) {
178+
table[row][column] = ciphertext.charAt(index++);
152179
}
153180
}
154181

155182
// Read the table row by row to reconstruct the fractionated text
156183
StringBuilder fractionatedText = new StringBuilder();
157-
for (char[] row : table) {
158-
for (char cell : row) {
159-
if (cell != '_') {
160-
fractionatedText.append(cell);
184+
for (int row = 0; row < numRows; row++) {
185+
for (int column = 0; column < numCols; column++) {
186+
if (row < columnLength[column]) {
187+
fractionatedText.append(table[row][column]);
161188
}
162189
}
163190
}

‎src/main/java/com/thealgorithms/geometry/GrahamScan.java‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,16 @@ public GrahamScan(Point[] points) {
4646
}
4747
}
4848

49-
hull.push(points[firstNonCollinearIndex - 1]);
49+
// Among the points collinear with points[0] on the first ray, only the farthest one
50+
// can be a hull vertex. The polar-order tie-break does not guarantee it sorts last
51+
// (horizontal ties sort by descending distance), so select it explicitly.
52+
Point farthestCollinear = points[firstNonEqualIndex];
53+
for (int i = firstNonEqualIndex + 1; i < firstNonCollinearIndex; i++) {
54+
if (distanceSquared(points[0], points[i]) > distanceSquared(points[0], farthestCollinear)) {
55+
farthestCollinear = points[i];
56+
}
57+
}
58+
hull.push(farthestCollinear);
5059

5160
// Process the remaining points and update the hull
5261
for (int i = firstNonCollinearIndex; i < points.length; i++) {
@@ -59,6 +68,12 @@ public GrahamScan(Point[] points) {
5968
}
6069
}
6170

71+
private static long distanceSquared(Point a, Point b) {
72+
long dx = a.x() - b.x();
73+
long dy = a.y() - b.y();
74+
return dx * dx + dy * dy;
75+
}
76+
6277
/**
6378
* @return An iterable collection of points representing the convex hull.
6479
*/
Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
package com.thealgorithms.machinelearning;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* SEFR (Simple, Effective and Fast linear classifieR).
7+
*
8+
* <p>SEFR trains a linear classifier in a single pass over the data, with no
9+
* iterations, no learning rate and no hyperparameters. It was designed for
10+
* training on very small devices such as microcontrollers.
11+
*
12+
* <p>For two classes, every feature is first min-max scaled to [0, 1] with the
13+
* training data. With {@code p[j]} and {@code n[j]} the means of feature
14+
* {@code j} over the positive and the negative samples, the weight is
15+
* {@code w[j] = (p[j] - n[j]) / (p[j] + n[j])}, so every weight lies in
16+
* [-1, 1]. The threshold {@code b} is the average of the two class mean scores
17+
* {@code w . x}, weighted by the size of the opposite class. A sample is
18+
* positive when {@code w . x - b > 0}.
19+
*
20+
* <p>Labels may be any integers. With two distinct labels, the larger one is
21+
* treated as the positive class. With more labels, one weight vector is
22+
* trained per label (one-vs-rest) and the label with the largest score
23+
* {@code w . x - b} is predicted.
24+
*
25+
* <p>Training takes O(samples * features + classes * features) time and the
26+
* model takes O(classes * features) space.
27+
*
28+
* @see <a href="https://arxiv.org/abs/2006.04620">SEFR: A Fast Linear-Time
29+
* Classifier for Ultra-Low Power Devices</a>
30+
*/
31+
public final class Sefr {
32+
private int[] classes;
33+
private double[][] weights;
34+
private double[] bias;
35+
private double[] featureMin;
36+
private double[] featureRange;
37+
38+
/**
39+
* Fits the classifier.
40+
*
41+
* @param features training samples, one row per sample, all rows of equal
42+
* length
43+
* @param labels class label of each row of {@code features}
44+
* @throws IllegalArgumentException if the inputs are empty, of different
45+
* lengths, not finite, or hold fewer than
46+
* two distinct labels
47+
*/
48+
public void fit(double[][] features, int[] labels) {
49+
if (features == null || labels == null || features.length == 0 || features.length != labels.length) {
50+
throw new IllegalArgumentException("features and labels must be non-empty and of equal length");
51+
}
52+
final int numFeatures = features[0].length;
53+
if (numFeatures == 0) {
54+
throw new IllegalArgumentException("samples must have at least one feature");
55+
}
56+
for (double[] row : features) {
57+
checkRow(row, numFeatures);
58+
}
59+
final int[] sortedLabels = Arrays.stream(labels).distinct().sorted().toArray();
60+
if (sortedLabels.length < 2) {
61+
throw new IllegalArgumentException("SEFR needs at least two distinct labels");
62+
}
63+
64+
final double[] min = features[0].clone();
65+
final double[] range = features[0].clone();
66+
for (double[] row : features) {
67+
for (int j = 0; j < numFeatures; j++) {
68+
min[j] = Math.min(min[j], row[j]);
69+
range[j] = Math.max(range[j], row[j]);
70+
}
71+
}
72+
for (int j = 0; j < numFeatures; j++) {
73+
range[j] -= min[j];
74+
if (range[j] == 0.0) {
75+
range[j] = 1.0;
76+
}
77+
}
78+
79+
// Two classes need a single weight vector, scored for the larger label.
80+
final int[] positives = sortedLabels.length == 2 ? new int[] {sortedLabels[1]} : sortedLabels;
81+
final double[][] scaled = new double[features.length][];
82+
for (int i = 0; i < features.length; i++) {
83+
scaled[i] = scale(features[i], min, range);
84+
}
85+
final double[][] w = new double[positives.length][];
86+
final double[] b = new double[positives.length];
87+
for (int k = 0; k < positives.length; k++) {
88+
w[k] = trainWeights(scaled, labels, positives[k]);
89+
b[k] = trainBias(scaled, labels, positives[k], w[k]);
90+
}
91+
92+
this.classes = sortedLabels;
93+
this.featureMin = min;
94+
this.featureRange = range;
95+
this.weights = w;
96+
this.bias = b;
97+
}
98+
99+
/**
100+
* Returns the score {@code w . x - b} of one sample for each weight vector.
101+
* With two classes there is a single score, positive for the larger label.
102+
*
103+
* @param sample feature vector with as many values as the training rows
104+
* @return one score per weight vector
105+
* @throws IllegalStateException if the classifier has not been fitted
106+
* @throws IllegalArgumentException if the sample has the wrong length or is
107+
* not finite
108+
*/
109+
public double[] decisionFunction(double[] sample) {
110+
if (weights == null) {
111+
throw new IllegalStateException("classifier has not been fitted");
112+
}
113+
checkRow(sample, featureMin.length);
114+
final double[] z = scale(sample, featureMin, featureRange);
115+
final double[] scores = new double[weights.length];
116+
for (int k = 0; k < weights.length; k++) {
117+
scores[k] = dot(weights[k], z) - bias[k];
118+
}
119+
return scores;
120+
}
121+
122+
/**
123+
* Predicts the label of one sample.
124+
*
125+
* @param sample feature vector with as many values as the training rows
126+
* @return the predicted label
127+
*/
128+
public int predict(double[] sample) {
129+
final double[] scores = decisionFunction(sample);
130+
if (classes.length == 2) {
131+
return scores[0] > 0.0 ? classes[1] : classes[0];
132+
}
133+
int best = 0;
134+
for (int k = 1; k < scores.length; k++) {
135+
if (scores[k] > scores[best]) {
136+
best = k;
137+
}
138+
}
139+
return classes[best];
140+
}
141+
142+
/**
143+
* Predicts the labels of several samples.
144+
*
145+
* @param samples feature vectors, one row per sample
146+
* @return the predicted label of each row
147+
*/
148+
public int[] predict(double[][] samples) {
149+
final int[] predictions = new int[samples.length];
150+
for (int i = 0; i < samples.length; i++) {
151+
predictions[i] = predict(samples[i]);
152+
}
153+
return predictions;
154+
}
155+
156+
/**
157+
* Returns a copy of the weight vectors, one row per weight vector, in the
158+
* min-max scaled feature space.
159+
*
160+
* @return the weights
161+
* @throws IllegalStateException if the classifier has not been fitted
162+
*/
163+
public double[][] getWeights() {
164+
if (weights == null) {
165+
throw new IllegalStateException("classifier has not been fitted");
166+
}
167+
final double[][] copy = new double[weights.length][];
168+
for (int k = 0; k < weights.length; k++) {
169+
copy[k] = weights[k].clone();
170+
}
171+
return copy;
172+
}
173+
174+
private static double[] trainWeights(double[][] scaled, int[] labels, int positive) {
175+
final int numFeatures = scaled[0].length;
176+
final double[] posSum = new double[numFeatures];
177+
final double[] negSum = new double[numFeatures];
178+
int numPos = 0;
179+
for (int i = 0; i < scaled.length; i++) {
180+
final double[] target = labels[i] == positive ? posSum : negSum;
181+
if (labels[i] == positive) {
182+
numPos++;
183+
}
184+
for (int j = 0; j < numFeatures; j++) {
185+
target[j] += scaled[i][j];
186+
}
187+
}
188+
final int numNeg = scaled.length - numPos;
189+
final double[] w = new double[numFeatures];
190+
for (int j = 0; j < numFeatures; j++) {
191+
final double p = posSum[j] / numPos;
192+
final double n = negSum[j] / numNeg;
193+
w[j] = p + n > 0.0 ? (p - n) / (p + n) : 0.0;
194+
}
195+
return w;
196+
}
197+
198+
private static double trainBias(double[][] scaled, int[] labels, int positive, double[] w) {
199+
double posScore = 0.0;
200+
double negScore = 0.0;
201+
int numPos = 0;
202+
for (int i = 0; i < scaled.length; i++) {
203+
final double s = dot(w, scaled[i]);
204+
if (labels[i] == positive) {
205+
posScore += s;
206+
numPos++;
207+
} else {
208+
negScore += s;
209+
}
210+
}
211+
final int numNeg = scaled.length - numPos;
212+
// Mean scores of each class, weighted by the size of the opposite class.
213+
return (numNeg * (posScore / numPos) + numPos * (negScore / numNeg)) / scaled.length;
214+
}
215+
216+
private static double[] scale(double[] row, double[] min, double[] range) {
217+
final double[] z = new double[row.length];
218+
for (int j = 0; j < row.length; j++) {
219+
z[j] = (row[j] - min[j]) / range[j];
220+
}
221+
return z;
222+
}
223+
224+
private static double dot(double[] a, double[] b) {
225+
double s = 0.0;
226+
for (int j = 0; j < a.length; j++) {
227+
s += a[j] * b[j];
228+
}
229+
return s;
230+
}
231+
232+
private static void checkRow(double[] row, int numFeatures) {
233+
if (row == null || row.length != numFeatures) {
234+
throw new IllegalArgumentException("every sample must have " + numFeatures + " features");
235+
}
236+
for (double v : row) {
237+
if (!Double.isFinite(v)) {
238+
throw new IllegalArgumentException("features must be finite numbers");
239+
}
240+
}
241+
}
242+
}

0 commit comments

Comments
 (0)