given a matrix n x n
, determine if the arrow is
directed to the target (x). There will be only 1 arrow ‘>’ and 1
target ‘x’ An empty spot will be denoted by a space ” “, the target with
a cross”x”, and the scope “>”
given matrix 4x4:
[
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '], --> return true
[' ', '>', ' ', 'x'],
[' ', ' ', ' ', ' ']
]
given matrix 4x4:
[
[' ', ' ', ' ', ' '],
[' ', '>', ' ', ' '], --> return false
[' ', ' ', ' ', 'x'],
[' ', ' ', ' ', ' ']
]
given matrix 4x4:
[
[' ', ' ', ' ', ' '],
[' ', 'x', '>', ' '], --> return false
[' ', '', ' ', ' '],
[' ', ' ', ' ', ' ']
]
In this example, only a 4x4 matrix was used, the problem will have matrices of dimensions from 2 to 7 Happy hacking as they say!
using Test
"""
只有 `>` 和 `x` 在同一行且 `>` 在 `x` 前,才返回 true
"""
#> "只有 `>` 和 `x` 在同一行且 `>` 在 `x` 前,才返回 true\n"
function solution(A::Matrix{Char})::Bool
= findfirst(==('>'), A) # 返回CartesianIndex{2}
arrow_indices = arrow_indices[1], arrow_indices[2]
arrowᵢ, arrowⱼ = findfirst(==('x'), A)
target_indices = target_indices[1], target_indices[2]
targetᵢ, targetⱼ
return arrowᵢ == targetᵢ && arrowⱼ < targetⱼ
end
#> solution (generic function with 1 method)
= [
A ' ' ' ' ' ' ' ' ' '
' ' ' ' ' ' ' ' ' '
' ' ' ' ' ' ' ' ' '
' ' ' ' '>' ' ' 'x'
' ' ' ' ' ' ' ' ' '
]
#> 5×5 Matrix{Char}:
#> ' ' ' ' ' ' ' ' ' '
#> ' ' ' ' ' ' ' ' ' '
#> ' ' ' ' ' ' ' ' ' '
#> ' ' ' ' '>' ' ' 'x'
#> ' ' ' ' ' ' ' ' ' '
@test solution(A) == true
#> Test Passed
#> Expression: solution(A) == true
#> Evaluated: true == true
library(tidyverse)
<- function(M) {
solution # 将M沿列展开为向量的一维坐标
<- match(">", M)
arrow_index <- match("x", M)
target_index
# 二维坐标中的行
<- arrow_index%%nrow(M)
arrow_i <- target_index%%nrow(M)
target_i
== target_i && arrow_index < target_index
arrow_i
}
<- c(rep(" ", 17), ">", " ", "x", rep(" ", 5)) %>%
M matrix(nrow = 5, ncol = 5, byrow = TRUE)
solution(M)
#> [1] TRUE
const solution = function (mtrx) {
for (let row of mtrx) {
let scope = row.indexOf('>');
let target = row.indexOf('x');
if (target > -1 && scope > -1 && scope < target) return true;
}return false;
;
}
console.log(solution([
' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', '>', ' ', 'x'],
[' ', ' ', '', ' ', ' ']
[; ]))
#> true