Nov 19

## Zeller’s Congruence in Java

You can use the Calendar class to get the day of the week for a particular date. But if you’re after an algorithm to do the same then Zeller’s congruence may be of interest to you.

Zeller’s congruence is an algorithm devised by Christian Zeller to calculate the day of the week for any Julian or Gregorian calendar date.

Here’s an implementation of the Zeller algorithm in Java.

```
Calendar today = Calendar.getInstance();
int day = today.get(Calendar.DATE);
int month = today.get(Calendar.MONTH) + 1;
int year = today.get(Calendar.YEAR);

if (month < 3) {
month += 12;
year -= 1;
}

int k = year % 100;
int j = year / 100;

// 0 = Saturday, 1 = Sunday, ...
int dayOfWeek = ((day + (((month + 1) * 26) / 10) +
k + (k / 4) + (j / 4)) + (5 * j)) % 7;
```

Hope this helps you implement Zeller in Java.

written by objects \\ tags: , , , , ,

Nov 15

## How to calculate the likeness or similarity of two strings?

The Levenshtein Distance is a metric for measuring the amount of difference between two strings. The following shows the algorithm implemented in Java.

```public class LevenshteinDistance
{
public static int levenshteinDistance(
CharSequence string1, CharSequence string2)
{
final int length1 = string1.length();
final int length2 = string2.length();
int[][] distance = new int[length1 + 1][length2 + 1];

for (int i=0; i<=length1; i++)
{
distance[i] = i;
}
for (int j = 0; j <= length2; j++)
{
distance[j] = j;
}

for (int i = 1; i <= length1; i++)
{
for (int j = 1; j <= length2; j++)
{
final char char1 = string1.charAt(i - 1);
final char char2 = string2.charAt(j - 1);
final int offset = (char1 == char2) ? 0 : 1;
distance[i][j] = Math.min(Math.min(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1),
distance[i - 1][j - 1] + offset);
}
}
return distance[length1][length2];
}
}
```

written by objects \\ tags: , ,