Skip to main content
summaryrefslogtreecommitdiffstats
blob: 45728af125182e69082fbfaf39e976b9af85b442 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*******************************************************************************
 * Copyright (c) 2006 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.help.internal.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

/*
 * Provides an algorithm for determining a recommended sequence of items that
 * satisfies a primary sequence and as many secondary sequences as possible.
 *
 * For example, this is used to determine the display order of books on the tocs
 * based on the active product's preferred order as well as all other products'
 * preferred orders.
 */
public class SequenceResolver {

	private List primaryList;
	private List[] secondaryLists;
	private ListIterator primaryIter;
	private ListIterator[] secondaryIters;
	private Set processedItems;

	/*
	 * Merges the given primary and secondary orderings such that all ordering
	 * conditions from the primary are satisfied, and as many secondary ordering
	 * conditions as reasonably possible are also satisfied. An ordering condition
	 * is a pair of adjacent items in any ordering.
	 *
	 * For example:
	 *
	 *    primary =             {b, d, f}
	 *    secondary[0] =        {c, d, e}
	 *    secondary[1] =        {a, b, c}
	 *    -------------------------------
	 *    result =     {a, b, c, d, e, f}
	 *
	 * The algorithm works in iterations, where at each iteration we determine
	 * the next element in the recommended sequence. We maintain a pointer for
	 * each ordering to keep track of what we've already ordered.
	 *
	 * To determine the next item, we locate the current element in each ordering.
	 * These are the candidates for the next item as the next item can only be
	 * one of these.
	 *
	 * The top candidates are selected from the list of candidates, where a top
	 * candidate is one that has the lowest rank (there can be many). Rank is
	 * determined by how many other candidates appear before that candidate
	 * item in all the orderings. That is, we find out how many items
	 * the orderings list before each candidate.
	 *
	 * If a candidate has no other candidates listed before it, it will be
	 * the next item. If there are many, the first one is selected. If one of
	 * the top candidates is from the primary ordering (can only be one), it is
	 * automatically selected.
	 *
	 * Using the top rank ensures that if there are conflicts, and that
	 * as many orderings as possible are satisfied. For example, if most orderings
	 * want x before y, but a few want the opposite, x will be placed before y.
	 */
	public List getSequence(List primary, List[] secondary) {
		primaryList = primary;
		secondaryLists = secondary;
		prepareDataStructures();
		List order = new ArrayList();
		Object item;
		while ((item = getNextItem()) != null) {
			processedItems.add(item);
			advanceIterator(primaryIter);
			for (int i=0;i<secondaryIters.length;++i) {
				advanceIterator(secondaryIters[i]);
			}
			order.add(item);
		}
		return order;
	}

	/*
	 * Create the data structures necessary for later operations.
	 */
	private void prepareDataStructures() {
		primaryIter = primaryList.listIterator();
		secondaryIters = new ListIterator[secondaryLists.length];
		for (int i=0;i<secondaryLists.length;++i) {
			secondaryIters[i] = secondaryLists[i].listIterator();
		}
		processedItems = new HashSet();
	}

	/*
	 * Determine the next item in the sequence based on the top
	 * candidate items.
	 */
	private Object getNextItem() {
		Candidate[] candidates = getTopCandidates();
		switch(candidates.length) {
		case 0:
			return null;
		case 1:
			return candidates[0].item;
		default:
			for (int i=0;i<candidates.length;++i) {
				if (candidates[i].isPrimary) {
					return candidates[i].item;
				}
			}
			return candidates[0].item;
		}
	}

	/*
	 * Retrieves the top candidates from all the available next item candidates.
	 * These are the candidates that have the lowest rank
	 */
	private Candidate[] getTopCandidates() {
		Candidate[] candidates = getEligibleCandidates();
		rankCandidates(candidates);
		if (candidates.length > 0) {
			int topRank = candidates[0].rank;
			for (int i=1;i<candidates.length;++i) {
				if (candidates[i].rank < topRank) {
					topRank = candidates[i].rank;
				}
			}
			List topCandidates = new ArrayList();
			for (int i=0;i<candidates.length;++i) {
				if (candidates[i].rank == topRank) {
					topCandidates.add(candidates[i]);
				}
			}
			return (Candidate[])topCandidates.toArray(new Candidate[topCandidates.size()]);
		}
		return candidates;
	}

	/*
	 * Returns all eligible candidates. A candidate is eligible if it does not
	 * conflict with the primary candidate. That is, if the primary candidate's list
	 * has that candidate after the primary candidate, it is contradicting the primary
	 * sequence and is not eligible.
	 */
	private Candidate[] getEligibleCandidates() {
		Candidate[] allCandidates = getAllCandidates();
		Candidate primary = null;
		for (int i=0;i<allCandidates.length;++i) {
			if (allCandidates[i].isPrimary) {
				primary = allCandidates[i];
				break;
			}
		}
		// if we have no primary candidate then they're all eligible
		if (primary != null) {
			List eligibleCandidates = new ArrayList(allCandidates.length);
			// primary candidate is always eligible
			eligibleCandidates.add(primary);
			Set primarySet = Collections.singleton(primary.item);
			for (int i=0;i<allCandidates.length;++i) {
				Candidate c = allCandidates[i];
				if (c != primary) {
					// does it contradict the primary sequence? if not, it is eligible
					if (countPrecedingItems(c.item, primary.src, primarySet) == 0) {
						eligibleCandidates.add(c);
					}
				}
			}
			return (Candidate[])eligibleCandidates.toArray(new Candidate[eligibleCandidates.size()]);
		}
		return allCandidates;
	}

	/*
	 * Retrieve all the candidates for the next item in sequence, with
	 * no duplicates.
	 */
	private Candidate[] getAllCandidates() {
		List candidates = new ArrayList();
		Object item = getNextItem(primaryIter);
		if (item != null) {
			Candidate c = new Candidate();
			c.item = item;
			c.isPrimary = true;
			c.src = primaryList;
			candidates.add(c);
		}
		for (int i=0;i<secondaryIters.length;++i) {
			item = getNextItem(secondaryIters[i]);
			if (item != null) {
				Candidate c = new Candidate();
				c.item = item;
				c.isPrimary = false;
				c.src = secondaryLists[i];
				if (!candidates.contains(c)) {
					candidates.add(c);
				}
			}
		}
		return (Candidate[])candidates.toArray(new Candidate[candidates.size()]);
	}

	/*
	 * Assign a rank to each of the given candidates. Rank is determined by
	 * how many preceding candidates appear before that candidate in the orderings.
	 * This essentially means how far back this item should be in the final
	 * sequence.
	 */
	private void rankCandidates(Candidate[] candidates) {
		// for quick lookup
		Set candidateItems = new HashSet();
		for (int i=0;i<candidates.length;++i) {
			candidateItems.add(candidates[i].item);
		}
		for (int i=0;i<candidates.length;++i) {
			Candidate c = candidates[i];
			for (int j=0;j<candidates.length;++j) {
				c.rank += countPrecedingItems(c.item, candidates[j].src, candidateItems);
			}
		}
	}

	/*
	 * Counts the number of elements from the given set that come before
	 * the given item in the given list.
	 */
	private int countPrecedingItems(Object item, List list, Set set) {
		int count = 0;
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			Object next = iter.next();
			if (next.equals(item)) {
				return count;
			}
			if (set.contains(next)) {
				++count;
			}
		}
		return 0;
	}

	/*
	 * Returns the next item available to this iterator, without moving it
	 * forward.
	 */
	private Object getNextItem(ListIterator iter) {
		if (iter.hasNext()) {
			Object next = iter.next();
			iter.previous();
			return next;
		}
		return null;
	}

	/*
	 * Advances the given iterator to the next item in its
	 * sequence that we haven't yet processed.
	 */
	private void advanceIterator(ListIterator iter) {
		while (iter.hasNext()) {
			Object item = iter.next();
			if (!processedItems.contains(item)) {
				iter.previous();
				break;
			}
		}
	}

	/*
	 * A candidate item; one that could potentially be the next one in the final
	 * sequence.
	 */
	private static class Candidate {
		public Object item;
		public boolean isPrimary;
		public int rank;
		public List src;

		@Override
		public boolean equals(Object obj) {
			return item.equals(obj);
		}

		@Override
		public int hashCode() {
			return item.hashCode();
		}
	}
}

Back to the top