-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patharrayReplace.R
executable file
·41 lines (40 loc) · 1.04 KB
/
arrayReplace.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.
#
# Example
#
# For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, the output should be
# arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3].
#
# Input/Output
#
# [execution time limit] 5 seconds (r)
#
# [input] array.integer inputArray
#
# Guaranteed constraints:
# 0 ≤ inputArray.length ≤ 104,
# 0 ≤ inputArray[i] ≤ 109.
#
# [input] integer elemToReplace
#
# Guaranteed constraints:
# 0 ≤ elemToReplace ≤ 109.
#
# [input] integer substitutionElem
#
# Guaranteed constraints:
# 0 ≤ substitutionElem ≤ 109.
#
# [output] array.integer
#
# [R] Syntax Tips
# inputArray <- list(1, 2, 1, 2, 1);
# elemToReplace = 2;
# substitutionElem = 1;
arrayReplace <- function(inputArray, elemToReplace, substitutionElem) {
inputArray <- as.vector(unlist(inputArray))
for (x in seq(1:uniqueN(elemToReplace))) {
inputArray[inputArray == elemToReplace[x]] <- substitutionElem[x]
}
return(inputArray)
}