Description

Write a function that when given a number >= 0, returns an Array of ascending length subarrays.

pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]

Note: the subarrays should be filled with 1s

Solutions

Julia


using Test

function pyramid(n::Int64)::Vector{Vector}
    # 等价的三种写法
    # [ones(Int, k) for k ∈ 1:n]
    # [fill(1, k) for k ∈ 1:n]
    [repeat([1], k) for k  1:n]
end
#> pyramid (generic function with 1 method)

@test pyramid(3) == [[1], [1, 1], [1, 1, 1]]
#> Test Passed
#>   Expression: pyramid(3) == [[1], [1, 1], [1, 1, 1]]
#>    Evaluated: Vector[[1], [1, 1], [1, 1, 1]] == [[1], [1, 1], [1, 1, 1]]

R

library(tidyverse)

pyramid <- function(n) {
    1:n %>%
        map(~rep(1, .x))
}

pyramid(3)
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 1 1
#> 
#> [[3]]
#> [1] 1 1 1

JavaScript

/**
 * @module Pyramid-Array
 * @file JS 中的 repeat 可以考虑 Array(n).fill()
 */

const repeat = require("../src/JavaScript/toolkit/Vector").repeat;

function pyramid(n) {
  return [...Array(n)].map((_, i) => repeat([1], i + 1));
}

console.log(pyramid(3));
#> [ [ 1 ], [ 1, 1 ], [ 1, 1, 1 ] ]