View source: R/countConnected.r
countConnected | R Documentation |
This function calculates the number of objects formed by one or more adjacent cells that touch on their edges (i.e., not just at a corner). One way to solve this (inefficiently) is using a "ink-spreading" algorithm that accumulates adjacent cells until all are accounted for, then counts this as a single component. This function uses an efficient solution based on the Euler characteristic.
countConnected(x, count = 1)
x |
Matrix |
count |
Value to count as a "presence" in the matrix. All other values will be assumed to be not part of a component. |
Inspired by an answer by Alon Amit to the question on Quora, "What are some programming problems that look hard at a first glance but are actually easy?".
An integer (the number of connected, non-conterminous components).
v <- c(
1, 1, 0, 1,
1, 1, 0, 0,
1, 0, 0, 0,
0, 0, 0, 1,
0, 0, 1, 1,
1, 0, 0, 0,
0, 0, 0, 0)
x <- matrix(v, ncol=4, byrow=TRUE)
x
countConnected(x)
## Not run:
# will break because of connection at a vertex
v <- c(
1, 1, 0, 1,
1, 1, 0, 0,
1, 0, 0, 0,
0, 0, 0, 1,
0, 0, 1, 1,
1, 0, 0, 0,
0, 1, 0, 0)
x <- matrix(v, ncol=4, byrow=TRUE)
x
countConnected(x)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.