在 Julia 中创建具有重复元素的数组 – repeat() 方法
repeat()
是 julia 中的内置函数,用于通过以指定次数重复指定数组元素来构造数组。
Syntax:
repeat(A::AbstractArray, counts::Integer…)
or
repeat(A::AbstractArray; inner, outer)
or
repeat(s::AbstractString, r::Integer)
or
repeat(c::AbstractChar, r::Integer)
Parameters:
- A::AbstractArray: Specified array.
- counts::Integer: Specified number of times each element get repeated.
- inner: It says the repetition of individual element.
- outer: It says the repetition of whole slice.
- s::AbstractString: Specified string.
- r::Integer: Specified number of times each element get repeated.
- c::AbstractChar: Specified character.
Returns: It returns a new constructed array.
示例 1:
# Julia program to illustrate
# the use of Array repeat() method
# Constructing an array by repeating
# the specified 1D array with the
# specified number of times.
A = [1, 2, 3, 4];
println(repeat(A, 1))
# Constructing an array by repeating
# the specified 1D array with the
# specified number of times.
B = [1, 2, 3, 4];
println(repeat(B, 1, 2))
# Constructing an array by repeating
# the specified 2D array with the
# specified number of times.
C = [1 2; 3 4];
println(repeat(C, 2))
# Constructing an array by repeating
# the specified 2D array with the
# specified number of times.
D = [1 2; 3 4];
println(repeat(D, 2, 2))
输出:
示例 2:
# Julia program to illustrate
# the use of Array repeat() method
# Constructing an array by repeating
# the specified elements with the
# specified inner value
println(repeat(1:3, inner = 2))
# Constructing an array by repeating
# the specified elements with the
# specified outer value
println(repeat(2:4, outer = 2))
# Constructing an array by repeating
# the specified elements with the
# specified inner and outer value
println(repeat([5 10; 15 20], inner =(2, 1), outer =(1, 3)))
输出:
示例 3:
# Julia program to illustrate
# the use of Array repeat() method
# Getting new string after repetition of
# specified string or character
println(repeat("GFG", 3))
println(repeat("GeeksforGeeks", 2))
println(repeat("a", 4))
println(repeat("A", 5))
输出:
GFGGFGGFG
GeeksforGeeksGeeksforGeeks
aaaa
AAAAA