Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]
function is_zero(arr::Vector)::Vector{Bool}
map(x -> x == 0 && typeof(x) != Bool, arr)
end
#> is_zero (generic function with 1 method)
function moveZeros(arr::Vector)::Vector
is_zero(arr)]..., arr[is_zero(arr)]...]
[arr[.!end
#> moveZeros (generic function with 1 method)
moveZeros([false, 1, 0, 1, 2, 0, 1, 3, "a"])
#> 9-element Vector{Any}:
#> false
#> 1
#> 1
#> 2
#> 1
#> 3
#> "a"
#> 0
#> 0
library(tidyverse)
<- function(arr) {
moveZeros c(arr %>%
keep(~!identical(.x, 0)), arr %>%
keep(~identical(.x, 0)))
}
moveZeros(c(1, 2, 0, 1, 0, 1, 0, 3, 0, 1))
#> [1] 1 2 1 1 3 1 0 0 0 0
moveZeros(list(FALSE, 1, 0, 1, 2, 0, 1, 3, "a"))
#> [[1]]
#> [1] FALSE
#>
#> [[2]]
#> [1] 1
#>
#> [[3]]
#> [1] 1
#>
#> [[4]]
#> [1] 2
#>
#> [[5]]
#> [1] 1
#>
#> [[6]]
#> [1] 3
#>
#> [[7]]
#> [1] "a"
#>
#> [[8]]
#> [1] 0
#>
#> [[9]]
#> [1] 0
function moveZeros(arr) {
// ...将数组中的所有元素展开,然后才是元素的串联,而非两个数组元素组成嵌套数组
return [...arr.filter(x => x !== 0), ...arr.filter(x => x === 0)];
}
console.log(moveZeros([false, 1, 0, 1, 2, 0, 1, 3, "a"]));
.exports = moveZeros; module
#> [
#> false, 1, 1,
#> 2, 1, 3,
#> 'a', 0, 0
#> ]