From 27ef1844cbad9b53283b6d1c0b7a08a4b4271d2a Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Mon, 20 Jan 2014 00:44:03 +0100 Subject: add rotate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- src/algorithms/arrays/Rotate.java | 66 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/algorithms/arrays/Rotate.java (limited to 'src/algorithms') diff --git a/src/algorithms/arrays/Rotate.java b/src/algorithms/arrays/Rotate.java new file mode 100644 index 0000000..22ba033 --- /dev/null +++ b/src/algorithms/arrays/Rotate.java @@ -0,0 +1,66 @@ +/** + * Copyright © 2014 Mattias Andrée (maandree@member.fsf.org) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package algorithms.arrays; + +import java.util.*; + + +/** + * Class for rotating arrays + */ +public class Rotate +{ + /* + * There are many thing you can change in this class to adapt it, for example, + * if you want in-place rotation, which probabily is a bit slower (even though + * it is less naïve), you can reverse the array, split it at the index 'steps', + * and reverse those partitions and the concatinate back again, of cause, you + * would only reverse parts of the array, not split and concatinate it. + * You could also reverse the array while rotating it, either reverse the + * input or the output. + */ + + +£[ $T = T ] && P=" " O=Object cast="(T[])" + /** + * Rotates an array + * + * @param items The array to rotate + * @param steps The number of steps to higher index to rotate elements + * @return The array rotated + */ +£>[ $T = T ] && + @SuppressWarnings("unchecked") + public static £{P}£{T}[] rotateClone(£{T}[] items, int steps) + { + £{O}[] rc = new £{O}[items.length]; + + int n = items.length; + if ((n & -n) == n) /* power of 2 */ + for (int i = 0, m = n - 1; i < n; i++) + rc[(steps + i) & m] = items[i]; + else + for (int i = 0; i < n; i++) + rc[(steps + i) % n] = items[i]; + + return £{cast}rc; + } +£>done +} + -- cgit v1.2.3-70-g09d2