Here you can find the source of normalize(int[] a)
Parameter | Description |
---|---|
a | the sequence to normalize |
public static int[] normalize(int[] a)
//package com.java2s; //License from project: Open Source License public class Main { /**//from w w w.j av a2 s . com * Normalize the sequence <tt>a</tt> by first shortening it to the shortest * subsequence which when repeated yields <tt>a</tt>, and then finding the * lexicographically largest of its shifts. * * For example: * [3,3,3] is normalized to [3] * [1,4,4,1,4,4] is normalized to [4,4,1] * * @param a the sequence to normalize * @return the normalized sequence */ public static int[] normalize(int[] a) { int len = a.length; for (int i = 1; i < len; i++) //ugly way to iterate over len's devisors { if (len % i == 0) { boolean cannot_be_cut = false; for (int j = 0; j < i; j++) { for (int k = 1; k < (len / i); k++) { if (a[j] != a[(j + i * k) % len]) { cannot_be_cut = true; break; } } if (cannot_be_cut) { break; } } if (!cannot_be_cut) { int[] aa = new int[i]; for (int j = 0; j < i; j++) aa[j] = a[j]; return order(aa); } } } return order(a); } /** * Returns the lexicographically largest of <tt>a</tt>'s shifts */ private static int[] order(int[] a) { int best_shift = 0; int len = a.length; for (int i = 1; i < len; i++) { if (compare_shift(a, i, best_shift) == 1) best_shift = i; } if (best_shift == 0) return a; int[] aa = new int[len]; for (int i = 0; i < len; i++) aa[i] = a[(i + best_shift) % len]; return aa; } /** * Checks if <tt>a</tt> shifted by <tt>s1</tt> is lexicographically * bigger, the same, or smaller than <tt>a</tt> sifted by <tt>s2</tt>. * Returns 1, 0 or -1 respectively. * * That is returns: * 1 if (a_s1) > (a_s2) * 0 if (a_s1) = (a_s2) *-1 if (a_s1) < (a_s2) */ private static int compare_shift(int[] a, int s1, int s2) { int len = a.length; for (int i = 0; i < a.length; i++) { if (a[(i + s1) % len] > a[(i + s2) % len]) return 1; else if (a[(i + s1) % len] < a[(i + s2) % len]) return -1; } return 0; } }