Ang*_*sky 5 arrays algorithm uniform
给定一个包含N个元素的数组,我正在寻找M(M <N)个连续的子阵列,这些子阵列的长度相等或长度大多相差1个.例如,如果N = 12且M = 4,则所有子阵列都会具有相等的N/M = 3的长度.如果N = 100且M = 12,我期望长度为8和9的子阵列,并且两个尺寸应该在原始阵列内均匀分布.这项简单的任务变得有点微妙.我想出了Bresenham的线算法的改编版,当用C++编码时,它看起来像这样:
/// The function suggests how an array with num_data-items can be
/// subdivided into successively arranged groups (intervals) with
/// equal or "similar" length. The number of intervals is specified
/// by the parameter num_intervals. The result is stored into an array
/// with (num_data + 1) items, each of which indicates the start-index of
/// an interval, the last additional index being a sentinel item which
/// contains the value num_data.
///
/// Example:
///
/// Input: num_data ........... 14,
/// num_intervals ...... 4
///
/// Result: result_start_idx ... [ 0, 3, 7, 10, 14 ]
///
void create_uniform_intervals( const size_t num_data,
const size_t num_intervals,
std::vector<size_t>& result_start_idx )
{
const size_t avg_interval_len = num_data / num_intervals;
const size_t last_interval_len = num_data % num_intervals;
// establish the new size of the result vector
result_start_idx.resize( num_intervals + 1L );
// write the pivot value at the end:
result_start_idx[ num_intervals ] = num_data;
size_t offset = 0L; // current offset
// use Bresenham's line algorithm to distribute
// last_interval_len over num_intervals:
intptr_t error = num_intervals / 2;
for( size_t i = 0L; i < num_intervals; i++ )
{
result_start_idx[ i ] = offset;
offset += avg_interval_len;
error -= last_interval_len;
if( error < 0 )
{
offset++;
error += num_intervals;
} // if
} // for
}
Run Code Online (Sandbox Code Playgroud)
该代码计算N = 100的间隔长度,M = 12:8 9 8 8 9 8 8 9 8 8 9 8
实际的问题是我不知道如何调用我的问题,所以我很难找到它.
我需要将算法作为更大的数据聚类算法的一部分.我认为它对于实现并行排序(?)也很有用.
如果你的语言有整数除法舍去,计算一个简单的方法部分的大小i是通过(N*i+N)/M - (N*i)/M.例如,python程序
N=100;M=12
for i in range(M): print (N*i+N)/M - (N*i)/M
Run Code Online (Sandbox Code Playgroud)
输出数字8 8 9 8 8 9 8 8 9 8 8 9. N=12;M=5输出2 2 3 2 3. N=12;M=3输出4 4 4.
如果您的节号是从1开始而不是从0开始,则表达式是相反的(N*i)/M - (N*i-N)/M.