countConnected: Count number of contiguous "blocks" of cells

View source: R/countConnected.r

countConnectedR Documentation

Count number of contiguous "blocks" of cells

Description

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.

Usage

countConnected(x, count = 1)

Arguments

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.

Details

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?".

Value

An integer (the number of connected, non-conterminous components).

Examples


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)


adamlilith/statisfactory documentation built on Jan. 3, 2024, 10:37 p.m.