Javascript group the numbers from an array with series of consecutive numbers
Iterate with Array#reduce
, and whenever the last number is not equal to the new number - 1, add another sub array. Add the current number to the last sub array:
const a = [0,1,2,5,6,9];
const result = a.reduce((r, n) => { const lastSubArray = r[r.length - 1]; if(!lastSubArray || lastSubArray[lastSubArray.length - 1] !== n - 1) { r.push([]); } r[r.length - 1].push(n); return r; }, []);
console.log(result);
group together consecutive numbers in a list
You could use negative indexing:
def group_by_missing(seq):
if not seq:
return seq
grouped = [[seq[0]]]
for x in seq[1:]:
if x == grouped[-1][-1] + 1:
grouped[-1].append(x)
else:
grouped.append([x])
return grouped
Example Usage:
>>> lst = [1, 2, 3, 4, 5, 12, 13, 14, 15, 20, 21, 22, 23, 30, 35, 36, 37, 38, 39, 40]
>>> group_by_missing(lst)
[[1, 2, 3, 4, 5], [12, 13, 14, 15], [20, 21, 22, 23], [30], [35, 36, 37, 38, 39, 40]]
How to count group of consecutive numbers in array
In the future, try to include more info on what you've tried or what you've researched. As Azro said, we're here to help, not complete tasks for you.
int[] myArr = {1,2,3,4,9,12,17,23,34,54,55,56};
int consecutiveSums = 0;
// Iterate through the array
for (int i = 0; i < myArr.length; i++) {
// Check if the next value is consecutive
if (i + 1 < myArr.length && myArr[i] + 1 == myArr[i+1]) {
consecutiveSums ++;
// Skip any remaining consecutives until we reach a new set
while (i + 1 < myArr.length && myArr[i] + 1 == myArr[i+1]) {
i++;
}
}
}
System.out.println(consecutiveSums);
Group the consecutive numbers from an array with series of numbers which are greater than 2 into subarrays using javascript
You can use a global variable to keep track of the indexes so that it's possible to detect when exists a gap between two numbers, which allows you to add another array. In combination, using ternary operators can make the code cleaner to test for conditions.
const arr = [1, 2, 3, 5, 6, 7, 8, 10, 0, 1, 1, 2, 4, 10, 6, 7, 3];
let lastIdx = -1
const results = arr.reduce((acc, current, idx) =>
(
current > 2 ? (
lastIdx + 1 === idx && acc.length ?
(
lastIdx = idx,
acc[acc.length - 1].push(current),
acc
)
:
(
lastIdx = idx,
[...acc, [current]]
)
) : acc
)
, [])
console.log(results);
Best way to loop through array and group consecutive numbers in another array SWIFT 4?
My suggestion is IndexSet
where consecutive items are stored as ranges.
- Create the index set from the array.
- Get the
rangeView
. - Map the ranges to arrays.
let myNumbersArray = [1,2,3,4,10,11,15,20,21,22,23]
let indexSet = IndexSet(myNumbersArray)
let rangeView = indexSet.rangeView
let newNumbersArray = rangeView.map { Array($0.indices) }
Grouping consecutive elements together using Javascript
You can use a counter variable which has to be incremented and the difference between the index and the consecutive elements are the same, group them in a temporary array. If the difference is varies for two consecutive array elements, the temporary element has to be moved to the result
and the temporary array has to be assigned a new array object.
var array = [2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20];
var result = [], temp = [], difference;
for (var i = 0; i < array.length; i += 1) {
if (difference !== (array[i] - i)) {
if (difference !== undefined) {
result.push(temp);
temp = [];
}
difference = array[i] - i;
}
temp.push(array[i]);
}
if (temp.length) {
result.push(temp);
}
console.log(result);
# [ [ 2, 3, 4, 5 ], [ 8, 9 ], [ 12, 13, 14, 15, 16, 17 ], [ 20 ] ]
Identify groups of continuous numbers in a list
more_itertools.consecutive_groups
was added in version 4.0.
Demo
import more_itertools as mit
iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
[list(group) for group in mit.consecutive_groups(iterable)]
# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]
Code
Applying this tool, we make a generator function that finds ranges of consecutive numbers.
def find_ranges(iterable):
"""Yield range of consecutive numbers."""
for group in mit.consecutive_groups(iterable):
group = list(group)
if len(group) == 1:
yield group[0]
else:
yield group[0], group[-1]
iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
list(find_ranges(iterable))
# [(2, 5), (12, 17), 20]
The source implementation emulates a classic recipe (as demonstrated by @Nadia Alramli).
Note: more_itertools
is a third-party package installable via pip install more_itertools
.
How to group consecutive data in 2d array in python
Here you go ...
Steps are:
- Get a list
xUnique
of unique column 1 values with sort order preserved. - Build a list
xRanges
of items of the form[col1_value, [col2_min, col2_max]]
holding the column 2 ranges for each column 1 value. - Build a list
xGroups
of items of the form[[col1_min, col1_max], [col2_min, col2_max]]
where the[col1_min, col1_max]
part is created by merging thecol1_value
part of consecutive items inxRanges
if they differ by 1 and have identical[col2_min, col2_max]
value ranges for column 2. - Turn the ranges in each item of
xGroups
into strings and print with the required row and column headings. - Also package and print as a
numpy.array
to match the form of the input.
import numpy as np
data = np.array([
[1, 1],
[1, 2],
[2, 1],
[2, 2],
[3, 1],
[5, 1],
[5, 2]])
xUnique = list({pair[0] for pair in data})
xRanges = list(zip(xUnique, [[0, 0] for _ in range(len(xUnique))]))
rows, cols = data.shape
iRange = -1
for i in range(rows):
if i == 0 or data[i, 0] > data[i - 1, 0]:
iRange += 1
xRanges[iRange][1][0] = data[i, 1]
xRanges[iRange][1][1] = data[i, 1]
xGroups = []
for i in range(len(xRanges)):
if i and xRanges[i][0] - xRanges[i - 1][0] == 1 and xRanges[i][1] == xRanges[i - 1][1]:
xGroups[-1][0][1] = xRanges[i][0]
else:
xGroups += [[[xRanges[i][0], xRanges[i][0]], xRanges[i][1]]]
xGroupStrs = [ [f'{a}-{b}' for a, b in row] for row in xGroups]
groupArray = np.array(xGroupStrs)
print(groupArray)
print()
print(f'{"":<10}{"Col1":<8}{"Col2":<8}')
[print(f'{"group " + str(i) + ":":<10}{col1:<8}{col2:<8}') for i, (col1, col2) in enumerate(xGroupStrs)]
Output:
[['1-2' '1-2']
['3-3' '1-1']
['5-5' '1-2']]
Col1 Col2
group 0: 1-2 1-2
group 1: 3-3 1-1
group 2: 5-5 1-2
Related Topics
How to Programmatically Check If a Certificate Has Been Revoked
Is There a Method to Limit/Clamp a Number
Ruby Scope of Data After _End_
How to Change Passenger Ruby Version Without Recompiling
Parsing Large Xml Files W/ Ruby & Nokogiri
What Is the Purpose of the Enumerator Class in Ruby
Why Does Hash.New({}) Hide Hash Members
Ruby Variable as Same Object (Pointers)
Ruby -V Dyld: Library Not Loaded: /Usr/Local/Lib/Libgmp.10.Dylib
Using Activerecord Find_In_Batches Method for Deleting Large Data
How to Delete a Range of Values from an Array
Why Do Ruby Procs/Blocks with Splat Arguments Behave Differently Than Methods and Lambdas
How to Use Escape Characters in Strings
Problems Keeping an Object in an Array, Ruby Issues and Rails Issues