Skip to content

Commit

Permalink
Merge pull request #332 from cicirello/optimize
Browse files Browse the repository at this point in the history
Refactored reverse, scramble, and swapBlocks methods of Permutation
  • Loading branch information
cicirello authored Apr 14, 2023
2 parents 1ec5eec + dead060 commit d112dcb
Show file tree
Hide file tree
Showing 5 changed files with 798 additions and 27 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased] - 2023-04-13
## [Unreleased] - 2023-04-14

### Added

### Changed
* Optimized or otherwise refactored for code quality the scramble, reverse, and swapBlocks methods of the Permutation class.

### Deprecated

Expand Down
26 changes: 14 additions & 12 deletions src/main/java/org/cicirello/permutations/Permutation.java
Original file line number Diff line number Diff line change
Expand Up @@ -539,10 +539,12 @@ public void scramble(int i, int j, RandomGenerator r) {
if (i == j) {
return;
}
int k = j;
int k;
if (i > j) {
k = i;
i = j;
} else {
k = j;
}
boolean changed = false;
for (; k > i + 1; k--) {
Expand Down Expand Up @@ -745,22 +747,20 @@ public void swapBlocks(int a, int b, int i, int j) {
// blocks are adjacent
removeAndInsert(i, j - i + 1, a);
} else {
int[] temp = new int[j - a + 1];
int[] temp = new int[j - b];
int k = j - i + 1;
System.arraycopy(permutation, i, temp, 0, k);
int m = i - b - 1;
System.arraycopy(permutation, b + 1, temp, k, m);
System.arraycopy(permutation, a, temp, k + m, b - a + 1);
System.arraycopy(permutation, a, permutation, a + temp.length, b - a + 1);
System.arraycopy(temp, 0, permutation, a, temp.length);
hashCodeIsCached = false;
}
}

/** Reverses the order of the elements in the permutation. */
public void reverse() {
for (int i = 0, j = permutation.length - 1; i < j; i++, j--) {
internalSwap(i, j);
}
internalReverse(0, permutation.length - 1);
hashCodeIsCached = false;
}

Expand All @@ -774,13 +774,9 @@ public void reverse() {
*/
public void reverse(int i, int j) {
if (i > j) {
for (; i > j; i--, j++) {
internalSwap(i, j);
}
internalReverse(j, i);
} else {
for (; i < j; i++, j--) {
internalSwap(i, j);
}
internalReverse(i, j);
}
hashCodeIsCached = false;
}
Expand Down Expand Up @@ -957,6 +953,12 @@ private boolean validate(int[] p) {
return true;
}

private void internalReverse(int i, int j) {
for (; i < j; i++, j--) {
internalSwap(i, j);
}
}

/*
* Use internally, such as from reverse, etc to avoid
* repeatedly invalidating hashCode cache (as well as from
Expand Down
Loading

0 comments on commit d112dcb

Please sign in to comment.