This commit is contained in:
narawat lamaiin
2025-03-31 21:30:29 +07:00
parent 562f528c01
commit 1da05f5cae
2 changed files with 63 additions and 19 deletions

View File

@@ -6,7 +6,7 @@ export timedifference, showstracktrace, findHighestIndexKey, uuid4snakecase, rep
dfToString, dataframe_to_json_list, dictToString, dictToString_noKey,
dictToString_numbering, extract_triple_backtick_text,
countGivenWords, remove_french_accents, detect_keyword, extractTextBetweenCharacter,
convertCamelSnakeKebabCase, fitrange, lastElementsIndex
convertCamelSnakeKebabCase, fitrange, recentElementsIndex, nonRecentElementsIndex
using JSON3, DataStructures, Distributions, Random, Dates, UUIDs, MQTTClient, DataFrames
@@ -1182,32 +1182,75 @@ end
""" Find a unit range for a vector given a number of the most recent elements of interest.
# Arguments
- `v::AbstractVector`
the input vector to extract recent elements from
- `vectorLength::Integer`
the length of the vector to generate range from
- `n::Integer`
the number of most recent elements to include in the range
the number of most recent elements to include in range
# Return
- `UnitRange`
a range representing the last `n` elements of the vector
a range representing the n most recent elements of a vector with length vectorLength
# Example
```jldoctest
julia> a = [1, 2, 3, 4, 5]
julia> lastElementsIndex(a, 3)
julia> recentElementsIndex(length(a), 3)
3:5
julia> recentElementsIndex(length(a), 0)
5:5
```
"""
function lastElementsIndex(v::AbstractVector, n::Integer)
len = length(v)
function recentElementsIndex(vectorlength::Integer, n::Integer)
if n == 0
return 1:len
error("n must be greater than 0")
end
start = max(1, len - n + 1)
return start:len
start = max(1, vectorlength - n + 1)
return start:vectorlength
end
""" Find a unit range for a vector excluding the most recent elements.
# Arguments
- `vectorlength::Integer`
the length of the vector to generate range from
- `n::Integer`
the number of most recent elements to exclude from range
# Return
- `UnitRange`
a range representing the elements of the vector excluding the last `n` elements
# Example
```jldoctest
julia> a = [1, 2, 3, 4, 5]
julia> nonRecentElementsIndex(length(a), 3)
1:2
julia> nonRecentElementsIndex(length(a), 1)
1:4
julia> nonRecentElementsIndex(length(a), 0)
1:5
```
"""
function nonRecentElementsIndex(vectorlength::Integer, n::Integer)
if n < 0
error("n must be non-negative")
end
if n > vectorlength
return 1:0 # empty range
end
return 1:(vectorlength-n)
end
end # module util