Related
I've been studying the quick union algorithm. the code below was the example for the implementation.
Can someone explain to me what happens inside the root method please?
public class quickUnion {
private int[] id;
public void QuickUnionUF(int N){
id = new int [N];
for(int i = 0; i < N; i++){
id[i] = i;
}
}
private int root(int i){
while (i != id[i]){
i = id[i];
}
return i;
}
public boolean connected(int p, int q){
return root(p) == root(q);
}
public void union(int p, int q){
int i = root(p);
int j = root(q);
id[i] = j;
}
}
The core principle of union find is that each element belongs to a disjoint set of elements. This means that, if you draw a forest (set of trees), the forest will contain all the elements, and no element will be in two different trees.
When building these trees, you can imagine that any node either has a parent or is the root. In this implementation of union find (and in most union find implementations), the parent of each element is stored in an array at that element's index. Thus the element equivalent to id[i] is the parent of i.
You might ask: what if i has no parent (aka is a root)? In this case, the convention is to set i to itself (i is its own parent). Thus, id[i] == i simply checks if we have reached the root of the tree.
Putting this all together, the root function traverses, from the start node, all the way up the tree (parent by parent) until it reaches the root. Then it returns the root.
As an aside:
In order for this algorithm to get to the root more quickly, general implementations will 'flatten' the tree: the fewer parents you need to get through to get to the root, the faster the root function will return. Thus, in many implementations, you will see an additional step where you set the parent of an element to its original grandparent (id[i] = id[id[i]]).
The main point of algorithm here is: always keep root of one vertex equals to itself.
Initialization: Init id[i] = i. Each vertex itself is a root.
Merge Root:
If we merge root 5 and root 6. Assume that we want to merge root 6 into root 5. So id[6] = 5. id[5] = 5. --> 5 is root.
If we continue to merge 4 to 6. id[4] = 4 -> base root. id[6] = 5. -> not base root. We continue to find: id[5] = 5 -> base root. so we assign id[4] = 6
In all cases, we always keep convention: if x is base root, id[x] == x That is the main point of algorithm.
From Pdf file provided in the course Union find
Root of i is id[id[id[...id[i]...]]].
according to the given example
public int root(int p){
while(p != id[p]){
p = id[p];
}
return p;
}
lets consider a situation :
The elements of id[] would look like
Now lets call
root(3)
The dry run of loop inside root method is:
To understand the role of the root method, one needs to understand how this data structure is helping to organise values into disjoint sets.
It does so by building trees. Whenever two independent values 𝑝 and 𝑞 are said to belong to the same set, 𝑝 is made a child of 𝑞 (which then is the parent of 𝑝). If however 𝑝 already has a parent, then we first move to that parent of 𝑝, and the parent of that parent, ...until we find an ancestor which has no parent. This is root(p), lets call it 𝑝'. We do the same with 𝑞 if it has a parent. Let's call that ancestor 𝑞'. Finally, 𝑝' is made a child 𝑞'. By doing that, we implicitly make the original 𝑝 and 𝑞 members of the same tree.
How can we know that 𝑝 and 𝑞 are members of the same tree? By looking up their roots. If they happen to have the same root, then they are necessarily in the same tree, i.e. they belong to the same set.
Example
Let's look at an example run:
QuickUnionUF array = new QuickUnionUF(10);
This will create the following array:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This array represents edges. The from-side of an edge is the index in the array (0..9), and the to-side of the same edge is the value found at that index (also 0..9). As you can see the array is initialised in a way that all edges are self-references (loops). You could say that every value is the root of its own tree (which has no other values).
Calling root on any of the values 0..9, will return the same number, as for all i we have id[i] == i. So at this stage root does not give us much.
Now, let's indicate that two values actually belong to the same set:
array.union(2, 9);
This will result in the assignment id[2] = 9 and so we get this array:
[0, 1, 9, 3, 4, 5, 6, 7, 8, 9]
Graphically, this established link be represented as:
9
/
2
If now we call root(2) we will get 9 as return value. This tells us that 2 is in the same set (i.e. tree) as 9, and 9 happens to get the role of root of that tree (that was an arbitrary choice; it could also have been 2).
Let's also link 3 and 4 together. This is a very similar case as above:
array.union(3, 4);
This assigns id[3] = 4 and results in this array and tree representation:
[0, 1, 9, 4, 4, 5, 6, 7, 8, 9]
9 4
/ /
2 3
Now let's make it more interesting. Let's indicate that 4 and 9 belong to the same set:
array.union(4, 9);
Still root(4) and root(9) just return those same numbers (4 and 9). Nothing special yet... The assignment is id[4] = 9. This results in this array and graph:
[0, 1, 9, 4, 9, 5, 6, 7, 8, 9]
9
/ \
2 4
/
3
Note how this single assignment has joined two distinct trees into one tree. If now we want to check whether 2 and 3 are in the same tree, we call
if (connected(2, 3)) /* do something */
Although we never said 2 and 3 belonged to the same set explicitly, it should be implied from the previous actions. connected will now use calls to root to imply that fact. root(2) will return 9, and also root(3) will return 9. We get to see what root is doing... it is walking upwards in the graph towards the root node of the tree it is in. The array has all the information needed to make that walk. Given an index we can read in the array which is the parent (index) of that number. This may have to be repeated to get to the grandparent, ...etc: It can be a short or long walk, depending how many "edges" there are between the given node and the root of the tree it is in.
/**
* Quick Find Java Implementation Eager's Approach
*/
package com.weekone.union.quickfind;
import java.util.Random;
/**
* #author Ishwar Singh
*
*/
public class UnionQuickFind {
private int[] itemsArr;
public UnionQuickFind() {
System.out.println("Calling: " + UnionQuickFind.class);
}
public UnionQuickFind(int n) {
itemsArr = new int[n];
}
// p and q are indexes
public void unionOperation(int p, int q) {
// displayArray(itemsArr);
int tempValue = itemsArr[p];
if (!isConnected(p, q)) {
itemsArr[p] = itemsArr[q];
for (int i = 0; i < itemsArr.length; i++) {
if (itemsArr[i] == tempValue) {
itemsArr[i] = itemsArr[q];
}
}
displayArray(p, q);
} else {
displayArray(p, q, "Already Connected");
}
}
public boolean isConnected(int p, int q) {
return (itemsArr[p] == itemsArr[q]);
}
public void connected(int p, int q) {
if (isConnected(p, q)) {
displayArray(p, q, "Already Connected");
} else {
displayArray(p, q, "Not Connected");
}
}
private void displayArray(int p, int q) {
// TODO Auto-generated method stub
System.out.println();
System.out.print("{" + p + " " + q + "} -> ");
for (int i : itemsArr) {
System.out.print(i + ", ");
}
}
private void displayArray(int p, int q, String message) {
System.out.println();
System.out.print("{" + p + " " + q + "} -> " + message);
}
public void initializeArray() {
Random random = new Random();
for (int i = 0; i < itemsArr.length; i++) {
itemsArr[i] = random.nextInt(9);
}
}
public void initializeArray(int[] receivedArr) {
itemsArr = receivedArr;
}
public void displayArray() {
System.out.println("INDEXES");
System.out.print("{p q} -> ");
for (int i : itemsArr) {
System.out.print(i + ", ");
}
System.out.println();
}
}
Main Class:-
/**
*
*/
package com.weekone.union.quickfind;
/**
* #author Ishwar Singh
*
*/
public class UQFClient {
/**
* #param args
*/
public static void main(String[] args) {
int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = 10;
UnionQuickFind unionQuickFind = new UnionQuickFind(n);
// unionQuickFind.initializeArray();
unionQuickFind.initializeArray(arr);
unionQuickFind.displayArray();
unionQuickFind.unionOperation(4, 3);
unionQuickFind.unionOperation(3, 8);
unionQuickFind.unionOperation(6, 5);
unionQuickFind.unionOperation(9, 4);
unionQuickFind.unionOperation(2, 1);
unionQuickFind.unionOperation(8, 9);
unionQuickFind.connected(5, 0);
unionQuickFind.unionOperation(5, 0);
unionQuickFind.connected(5, 0);
unionQuickFind.unionOperation(7, 2);
unionQuickFind.unionOperation(6, 1);
}
}
Output:
INDEXES
{p q} -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
{4 3} -> 0, 1, 2, 3, 3, 5, 6, 7, 8, 9,
{3 8} -> 0, 1, 2, 8, 8, 5, 6, 7, 8, 9,
{6 5} -> 0, 1, 2, 8, 8, 5, 5, 7, 8, 9,
{9 4} -> 0, 1, 2, 8, 8, 5, 5, 7, 8, 8,
{2 1} -> 0, 1, 1, 8, 8, 5, 5, 7, 8, 8,
{8 9} -> Already Connected
{5 0} -> Not Connected
{5 0} -> 0, 1, 1, 8, 8, 0, 0, 7, 8, 8,
{5 0} -> Already Connected
{7 2} -> 0, 1, 1, 8, 8, 0, 0, 1, 8, 8,
{6 1} -> 1, 1, 1, 8, 8, 1, 1, 1, 8, 8,
How do I filter a publisher for the elements having the highest value without knowing the highest value beforehand?
Here is a little test to illustrate what I'm trying to achieve:
#Test
fun filterForHighestValuesTest() {
val numbers = Flux.just(1, 5, 7, 2, 8, 3, 8, 4, 3)
// what operators to apply to numbers to make the test pass?
StepVerifier.create(numbers)
.expectNext(8)
.expectNext(8)
.verifyComplete()
}
Ive started with the reduce operator:
#Test
fun filterForHighestValuesTestWithReduce() {
val numbers = Flux.just(1, 5, 7, 2, 8, 3, 8, 4, 3)
.reduce { a: Int, b: Int -> if( a > b) a else b }
StepVerifier.create(numbers)
.expectNext(8)
.verifyComplete()
}
and of course that test passes but that will only emit a single Mono whereas I would like to obtain a Flux containing all the elements having the highest values e.g. 8 and 8 in this simple example.
First of all, you'll need state for this so you need to be careful to have per-Subscription state. One way of ensuring that while combining operators is to use compose.
Proposed solution
Flux<Integer> allMatchingHighest = numbers.compose(f -> {
AtomicInteger highestSoFarState = new AtomicInteger(Integer.MIN_VALUE);
AtomicInteger windowState = new AtomicInteger(Integer.MIN_VALUE);
return f.filter(v -> {
int highestSoFar = highestSoFarState.get();
if (v > highestSoFar) {
highestSoFarState.set(v);
return true;
}
if (v == highestSoFar) {
return true;
}
return false;
})
.bufferUntil(i -> i != windowState.getAndSet(i), true)
.log()
.takeLast(1)
.flatMapIterable(Function.identity());
});
Note the whole compose lamdba can be extracted into a method, making the code use a method reference and be more readable.
Explaination
The solution is done in 4 steps, with the two first each having their own AtomicInteger state:
Incrementally find the new "highest" element (so far) and filter out elements that are smaller. This results in a Flux<Integer> of (monotically) increasing numbers, like 1 5 7 8 8.
buffer by chunks of equal number. We use bufferUntil instead of window* or groupBy because the most degenerative case were numbers are all different and already sorted would fail with these
skip all buffers but one (takeLast(1))
"replay" that last buffer, which represents the number of occurrences of our highest value (flatMapIterable)
This correctly pass your StepVerifier test by emitting 8 8. Note the intermediate buffers emitted are:
onNext([1])
onNext([5])
onNext([7, 7, 7])
onNext([8, 8])
More advanced testing, justifying bufferUntil
A far more complex source that would fail with groupBy but not this solution:
Random rng = new Random();
//generate 258 numbers, each randomly repeated 1 to 10 times
//also, shuffle the whole thing
Flux<Integer> numbers = Flux
.range(1, 258)
.flatMap(i -> Mono.just(i).repeat(rng.nextInt(10)))
.collectList()
.map(l -> {
Collections.shuffle(l);
System.out.println(l);
return l;
})
.flatMapIterable(Function.identity())
.hide();
This is one example of what sequence of buffers it could filter into (keep in mind only the last one gets replayed):
onNext([192])
onNext([245])
onNext([250])
onNext([256, 256])
onNext([257])
onNext([258, 258, 258, 258, 258, 258, 258, 258, 258])
onComplete()
Note: If you remove the map that shuffles, then you obtain the "degenerative case" where even windowUntil wouldn't work (the takeLast would result in too many open yet unconsumed windows).
This was a fun one to come up with!
One way to do it is to map the flux of ints to a flux of lists with one int in each, reduce the result, and end with flatMapMany, i.e.
final Flux<Integer> numbers = Flux.just(1, 5, 7, 2, 8, 3, 8, 4, 3);
final Flux<Integer> maxValues =
numbers
.map(
n -> {
List<Integer> list = new ArrayList<>();
list.add(n);
return list;
})
.reduce(
(l1, l2) -> {
if (l1.get(0).compareTo(l2.get(0)) > 0) {
return l1;
} else if (l1.get(0).equals(l2.get(0))) {
l1.addAll(l2);
return l1;
} else {
return l2;
}
})
.flatMapMany(Flux::fromIterable);
One simple solution that worked for me -
Flux<Integer> flux =
Flux.just(1, 5, 7, 2, 8, 3, 8, 4, 3).collectSortedList(Comparator.reverseOrder()).flatMapMany(Flux::fromIterable);
StepVerifier.create(flux).expectNext(8).expectNext(8).expectNext(7).expectNext(5);
One possible solution is to group the Flux prior to the reduction and flatmap the GroupedFlux afterwards like this:
#Test
fun filterForHighestValuesTest() {
val numbers = Flux.just(1, 5, 7, 2, 8, 3, 8, 4, 3)
.groupBy { it }
.reduce { t: GroupedFlux<Int, Int>, u: GroupedFlux<Int, Int> ->
if (t.key()!! > u.key()!!) t else u
}
.flatMapMany {
it
}
StepVerifier.create(numbers)
.expectNext(8)
.expectNext(8)
.verifyComplete()
}
Let us say I have [1,2,3,4,5,6,7] array, I need to split into it so that I always have 3 objects, i.e. [1,2,3], [4,5,6] , [5,6,7] on clicking next in the page. How to achieve this using start index and limitTo feature of angularjs?
Checking against the length of the array in your ng-click handler would be the way I'd go about this.
Something like the following:
$scope.items = [1, 2, 3, 4, 5, 6, 7];
$scope.startFrom = 0;
$scope.nextPage = function () {
if ($scope.startFrom + 3 > $scope.items.length - 3) {
$scope.startFrom = $scope.items.length - 3;
}
else {
$scope.startFrom += 3;
}
};
And then:
ng-repeat="item in items | limitTo: 3: startFrom"
If you have any problems with startFrom you may need to check your version of Angular. See this post for more info.
I wonder what would be the correct way to replace (overwriting) a part of a given std::vector "input" by another, smaller std::vector?
I do neet to keep the rest of the original vector unchanged.
Also I do not need to bother what has been in the original vector and
I don't need to keep the smaller vector afterwards anymore.
Say I have this:
std::vector<int> input = { 0, 0, 1, 1, 2, 22, 3, 33, 99 };
std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6, 7, 8 };
And I want to achieve that:
input = { 1, 2, 3, 4, 5, 6, 7, 8, 99}
What is the right way to do it? I thought of something like
input.replace(input.beginn(), input.beginn()+a.size(), a);
// intermediate input would look like that: input = { 1, 2, 3, 1, 2, 22, 3, 33, 99 };
input.replace(input.beginn()+a.size(), input.beginn()+a.size()+b.size(), b);
There should be a standard way to do it, shouldn't it?
My thoughts on this so far are the following:
I can not use std::vector::assign for it destroys all elements of input
std::vector::push_back would not replace but enlarge the input --> not what I want
std::vector::insert also creates new elements and enlages the input vector but I know for sure that the vectors a.size() + b.size() <= input.size()
std::vector::swap would not work since there is some content of input that needs to remain there ( in the example the last element) also it would not work to add b that way
std::vector::emplace also increases the input.size -> seems wrong as well
Also I would prefer if the solution would not waste performance by unnecessary clears or writing back values into the vectors a or b. My vectors will be very large for real and this is about performance in the end.
Any competent help would be appreciated very much.
You seem to be after std::copy(). This is how you would use it in your example (live demo on Coliru):
#include <algorithm> // Necessary for `std::copy`...
// ...
std::vector<int> input = { 0, 0, 1, 1, 2, 22, 3, 33, 99 };
std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6, 7, 8 };
std::copy(std::begin(a), std::end(a), std::begin(input));
std::copy(std::begin(b), std::end(b), std::begin(input) + a.size());
As Zyx2000 notes in the comments, in this case you can also use the iterator returned by the first call to std::copy() as the insertion point for the next copy:
auto last = std::copy(std::begin(a), std::end(a), std::begin(input));
std::copy(std::begin(b), std::end(b), last);
This way, random-access iterators are no longer required - that was the case when we had the expression std::begin(input) + a.size().
The first two arguments to std::copy() denote the source range of elements you want to copy. The third argument is an iterator to the first element you want to overwrite in the destination container.
When using std::copy(), make sure that the destination container is large enough to accommodate the number of elements you intend to copy.
Also, the source and the target range should not interleave.
Try this:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> input = { 0, 0, 1, 1, 2, 22, 3, 33, 99 };
std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6, 7, 8 };
std::set_union( a.begin(), a.end(), b.begin(), b.end(), input.begin() );
for ( std::vector<int>::const_iterator iter = input.begin();
iter != input.end();
++iter )
{
std::cout << *iter << " ";
}
return 0;
}
It outputs:
1 2 3 4 5 6 7 8 99
I am trying to convert this PHP validation code to ColdFusion. However, I cannot get my CF version to correctly validate a VIN. I am hoping someone can shed some light on what I'm missing.
<cfscript>
function isVIN(v) {
var i = "";
var d = "";
var checkdigit = "";
var sum = 0;
var weights = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];
var transliterations = {
a = 1,
b = 2,
c = 3,
d = 4,
e = 5,
f = 6,
g = 7,
h = 8,
j = 1,
k = 2,
l = 3,
m = 4,
n = 5,
p = 7,
r = 9,
s = 2,
t = 3,
u = 4,
v = 5,
w = 6,
x = 7,
y = 8,
z = 9
};
if (! REFindNoCase("^([\w]{3})[A-Z]{2}\d{2}([A-Z]{1}|\d{1})([\d{1}|X{1})([A-Z]+\d+|\d+[A-Z]+)\d{5}$", ARGUMENTS.v)) {
return false;
}
if (Len(ARGUMENTS.v) != 17) {
return false;
}
for (i = 1; i <= Len(ARGUMENTS.v); i++) {
d = Mid(ARGUMENTS.v, i, 1);
if (! isNumeric(d)) {
sum += transliterations[d] * weights[i];
} else {
sum += d * weights[i];
}
}
checkdigit = sum % 11;
if (checkdigit == 10) {
checkdigit = "x";
}
if (checkdigit == Mid(ARGUMENTS.v,8,1)) {
return true;
}
return false;
}
</cfscript>
(There is a VIN validation function at CFLib.org, but it doesn't work either).
Your function has two issues.
First, the regex is incorrect. Here's a simplified working version:
^[A-Z\d]{3}[A-Z]{2}\d{2}[A-Z\d][\dX](?:[A-Z]+\d+|\d+[A-Z]+)\d{5}$
Note: As per Adam's answer there's a simpler pattern than this.
Second, in your checkdigit comparison the Mid is one out - it seems the 8 should be a 9.
(Presumably this is a language conversion issue due to PHP being 0-indexed whilst CFML is 1-indexed.)
With both of these fixed, the modified function returns true for the VIN WAUBA24B3XN104537 (which is the only sample VIN I could find in a quick search).
Actually the regex is slightly wrong still. I think #PeterBoughton fixed the syntax, but it wasn't actually valid for the task at hand.
Here's the revised section of code, with suitable comments:
var vinRegex = "(?x) ## allow comments
^ ## from the start of the string
## see http://en.wikipedia.org/wiki/Vehicle_Identification_Number for VIN spec
[A-Z\d]{3} ## World Manufacturer Identifier (WMI)
[A-Z\d]{5} ## Vehicle decription section (VDS)
[\dX] ## Check digit
[A-Z\d] ## Model year
[A-Z\d] ## Plant
\d{6} ## Sequence
$ ## to the end of the string
";
if (! REFindNoCase(vinRegex, arguments.v)) {
return false;
}
This could be dramatically simplified to just this:
^[A-Z\d]{8}[\dX][A-Z\d]{2}\d{6}$
Using either of these also removes the requirement for the length check, as the regex will enforce that too.
Test code for this modification:
for (vin in [
"1GNDM19ZXRB170064",
"1FAFP40634F172825"
]){
writeOutput("#vin#: #isVin(vin)#<br />");
}
I'm gonna update CFLib with the verbose version, as it's easier to understand what's going on, and marry-up to the spec.