删除指定的非数字行


16

如有任何疑问:Nan = Non-numeric datatype就本挑战而言。


编写一个将矩阵/数组作为输入以及列索引列表的程序或函数。

面临的挑战是删除指定列中所有元素所在的行Nan。该行中的其他元素是否为数字都没有关系。以下示例有望使这一点更加清晰(它是一个索引的):

Input array:
    16   NaN     3    13
     5    11   NaN     8
   NaN     7   NaN    12
     4    14   -15     1

Input column index: [1 3]

Output array:
16   NaN     3    13
 5    11   NaN     8
 4    14   -15     1

----

Input array:
    16   NaN     3    13
     5    11   NaN     8
   NaN     7   NaN    12
     4    14   -15     1

Input column index: 3

Output array =
    16   NaN     3    13
     4    14   -15     1

----

Input array:
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

Input column index: 1 2 4

Output array:
 []

规则和说明:

  • 矩阵将始终为非空
  • 数值将是有限的,但不一定是整数或正值
  • 列索引向量可以为空(在这种情况下,不会删除任何行)
  • 列索引的值永远不会超过矩阵尺寸
  • 您可以假设列索引列表中不会重复
  • 您可以选择是否要使用零索引或一索引值(请指定)
  • 您可以采用任何方便的格式输入
    • 排列为列表列表即可。列索引可以是单独的参数
  • ans = 类似的在输出中被接受
  • 您可以自由选择要使用的非数字数据类型
    • 使用此数据类型执行算术运算,或使用诸如之类的函数将其转换为有限数量应该是不可能的float(x)

这是代码高尔夫,因此以字节为单位的最短代码获胜。

Answers:


6

Pyth,16 19 10 9 7 10字节

列索引从零开始。输入是列表列表。将空字符串用作非数字值。在第一行获取列索引列表,在第二行获取具有矩阵值的矩阵列表。

?Qf-QxkTEE

在线尝试!

说明

?Qf-QxkTEE       # Implicit: Q=column indices, E=Matrix

?Q       E       # If column list is empty no rows get removed
  f     E        # filter the given matrix by each row T
     xkT         # Get the indices of all occurences of an emtpy string (k) 
   -Q            # If the indices match with the given column indices, remove the row

更新:我的第一个解决方案处理了一个空的列索引列表错误。修复了它(非常难看),花费了3个字节。下班后要努力做得更好...

更新2:在 @FryAmTheEggman的帮助下,通过大幅改进算法,将其压缩为10 9 7字节。

Update3:修复了发现@ThomasKwa的错误。他提出的7字节解决方案不能正确处理空列索引,因此我在这里仅用三进制来解决这种情况。我看不到如何缩短自动取款机。


1
您可以替换J使用vz,并KQz初始化为输入,Q为求值输入。
PurkkaKoodari '02

@ Pietu1998非常感谢!:)我知道我在这方面缺少一些东西。可悲的是,当我再次查看该错误以实现您的建议时,我发现了一个错误,这总体上增加了我的字节数,直到找到更好的解决方案为止。
Denker

1
?KEfnmklKm@TdKQQ空列表在Pyth中是虚假的,赋值语句返回分配的值,这节省了一些字节。希望您喜欢Pyth打高尔夫球!:)
FryAmTheEggman '16

@FryAmTheEggman感谢您的建议。自从我对算法进行了很多改进以来,它不再具有实际意义,但是我非常感谢您的帮助!:)
Denker

非常好:)您可以使用L->fnks@LTQE
FryAmTheEggman

6

JavaScript(ES6),48个 46字节

(a,l)=>a.filter(r=>l.some(c=>r[a=0,c]<1/0)||a)

说明

期望将行数组作为数组,并将0索引数字数组作为要检查的列。返回数组的数组。

直截了当filtersomeNaN通过使用检查n < Infinitytrue对于有限数,false对于NaNs)。

var solution =

(a,l)=>
  a.filter(r=>     // for each row r
    l.some(c=>     // for each column to check c
      r[a=0,       // set a to false so we know the some was executed
        c]<1/0     // if any are not NaN, do not remove the row
    )
    ||a            // default to a because if l is of length 0, some returns false but
  )                //     we must return true
<textarea id="matrix" rows="5" cols="40">16 NaN 3 13
5 11 NaN 8
NaN 7 NaN 12
4 14 -15 1</textarea><br />
<input type="text" id="columns" value="0 2" />
<button onclick="result.textContent=solution(matrix.value.split('\n').map(l=>l.split(' ').map(n=>+n)),(columns.value.match(/\d+/g)||[]).map(n=>+n)).join('\n')">Go</button>
<pre id="result"></pre>


很好地处理了这种边缘情况!
尼尔

3

CJam,18个字节

{{1$\f=_!\se|},\;}

一个未命名的块(函数),该矩阵在堆栈上期望矩阵和从零开始的列索引(矩阵在顶部),从而将过滤后的矩阵留在堆栈上。我将空数组""用作非数字值。

在这里测试。

说明

{     e# Filter the matrix rows based on the result of this block...
  1$  e#   Copy the column indices.
  \f= e#   Map them to the corresponding cell in the current row.
  _!  e#   Duplicate, logical NOT. Gives 1 for empty column list, 0 otherwise.
  \s  e#   Convert other copy to string. If the array contained only empty arrays, this 
      e#   will be an empty string which is falsy. Otherwise it will contain the numbers 
      e#   that were left after filtering, so it's non-empty and truthy.
  e|  e#   Logical OR.
},
\;    e# Discard the column indices.

我是在测试错误还是违反了关于没有给定列索引的规则?The column index vector can be empty (in which case no rows will be removed)
Denker

@DenkerAffe Damn,固定为5个字节的成本...
Martin Ender

我也在那里...你仍然在我之前一个字节,所以我的计划还没有制定出来:P
Denker

“空数组""”是指“空字符串”吗?
ETHproductions '02

@ETHproductions CJam没有任何区别。字符串的字符数组只是,所以[]""是相同的,规范的表示是""(例如,它是当你字符串化空数组你会得到什么)。
Martin Ender

3

APL,19个字节

{⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]}

左边的参数应该是索引列表(并且它必须是列表,而不是标量),右边的参数是矩阵。APL有两种数据类型,数字和字符,因此可以过滤掉字符类型。

测试:

      m1 m2
   16  NaN    3  13   NaN  NaN  NaN  NaN  
    5   11  NaN   8   NaN  NaN  NaN  NaN  
  NaN    7  NaN  12   NaN  NaN  NaN  NaN  
    4   14  ¯15   1   NaN  NaN  NaN  NaN  
      1 3 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m1
16  NaN    3  13
 5   11  NaN   8
 4   14  ¯15   1
      (,3) {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m1
16  NaN    3 13
 4   14  ¯15  1
      1 2 4 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m2 ⍝ this shows nothing
      ⍴1 2 4 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m2 ⍝ the nothing is in fact a 0-by-4 matrix
0 4

说明:

  • ⍵[;⍺]:从矩阵中选择给定的列
  • 0↑¨:首先 0从每个项目的开头开始元素
  • ⍬∘≡¨:与数字空列表比较
  • ∨/:查看至少有一项与哪几行匹配
  • ⍵⌿⍨:从矩阵中选择那些行

2

MATLAB,32 28字节

我将回答我自己的问题一次。我在MATLAB中能做的最好的事情是28个字节。我希望避免同时使用all,并isnan以某种方式,但还没有找到一种方法呢。

@(A,c)A(any(A(:,c)<inf,2),:)

测试:

A =
    35     1   NaN   NaN   NaN    24
     3    32   NaN    21    23    25
    31   NaN   NaN   NaN    27    20
   NaN    28   NaN    17   NaN    15
    30     5   NaN    12    14   NaN
     4    36   NaN    13    18    11

f(A,[3,5])
ans =
     3    32   NaN    21    23    25
    31   NaN   NaN   NaN    27    20
    30     5   NaN    12    14   NaN
     4    36   NaN    13    18    11

这是一个未命名的匿名函数,它将输入矩阵作为第一个输入变量,并将列索引列表作为第二个输入变量。

在MATLAB中,NaN < Inf评估为false。可以假设所有值都是有限的,因此检查值是否小于inf等于检查它们是否为非数字。any(...,2)检查第二维(行)上是否有真值。如果是这种情况,那么将返回这些行。

旧版本:

@(A,c)A(~all(isnan(A(:,c)),2),:)

isnan(A(:,c))为指定的列返回一个带有布尔值的数组。~all(isnan(A(:,c)),2)检查第二维(行)上的所有值是否均为非数字,并将其取反。这将产生一个布尔矢量,在我们想要保留的位置上有一个。A(~all(isnan(A(:,c)),2),:)使用逻辑索引提取的全部行A


如果值保证为非零,则以下24字节解决方案将起作用:

@(A,c)A(any(A(:,c),2),:)

2

Ruby,48个字节

->a,c{a.select{|r|c.map{|i|Fixnum===r[i]}.any?}}

输入是从0开始的索引1

实际上,这是不言自明的。select来自数组的元素,其中在行上遍历的any?索引mapFixnums。

样品运行:

irb(main):010:0> (->a,c{a.select{|r|c.map{|i|Fixnum===r[i]}.any?}})[[[16,'',3,13],[5,11,'',8],['',7,'',12],[4,14,-15,1]],[0,2]]
=> [[16, "", 3, 13], [5, 11, "", 8], [4, 14, -15, 1]]

1:我终于在第一次尝试中正确拼写了这个单词!\ o /


2

K5,15个字节

这使用0索引列和K的自然列表列表表示形式:

{x@&~&/'^x[;y]}

在矩阵(x@)中将行索引到其中(&)并非每个(~&/')并非全部为空(^)的行。

实际上:

  m: (16 0N 3 13;5 11 0N 8;0N 7 0N 12;4 14 -15 1);
  f: {x@&~&/'^x[;y]};

  f[m;0 2]
(16 0N 3 13
 5 11 0N 8
 4 14 -15 1)

  f[m;2]
(16 0N 3 13
 4 14 -15 1)

2

MATL,15 16字节

tiZ)tn?ZN!XA~Y)

NaN在输入中表示为N。索引基于1。例如,在第一个测试案例中,输入为

[16 N 3 13; 5 11 N 8; N 7 N 12; 4 14 -15 1]
[1 3]

在线尝试!

说明

t       % implicitly input matrix, M. Duplicate
i       % input vector specifying columns
Z)      % matrix N containing those columns of M
tn?     % duplicate matrix N. If non-empty ...
  ZN    %   true for NaN values in matrix N
  !     %   transpose
  XA    %   "all" within each column: gives true for rows of N that contained all NaN's
  ~     %   logical negate
  Y)    %   apply this logical index as a row index into the copy of M that was left
        %   at the bottom of the stack
        % ... implicitly end if
        % implictly display stack contents. If the input vector was empty, the stack
        % contains the original matrix M and an empty matrix. The latter produces no
        % displayed output. If the input vector was non-empty, the stack contains the
        % resulting matrix N

2

R,49个字节

function(m,j)m[!!rowSums(!is.nan(m[,j,drop=F])),]

输入基于1。该函数采用一个矩阵(m)和一个j可能缺少的列索引()的向量。

两个测试用例:

> f <- function(m,j)m[!!rowSums(!is.nan(m[,j,drop=F])),]
> f(m)   
      V1  V2  V3 V4
[1,]  16 NaN   3 13
[2,]   5  11 NaN  8
[3,] NaN   7 NaN 12
[4,]   4  14 -15  1

> f(m, c(1,3))
     V1  V2  V3 V4
[1,] 16 NaN   3 13
[2,]  5  11 NaN  8
[3,]  4  14 -15  1

0

Lua,148字节

该函数以矩阵和数组为输入,并输出具有相应行的矩阵nil。由于数组与C的数组完全相同,free()因此,由于垃圾收集器就在不远的地方,因此进行虚空化就好了。

数组在Lua中是1索引的,我使用字符串"NaN"作为非Nomber元素。

function f(m,l)c=1 while(c<#m)do x=0 for j=1,#l do x=x+((type(m[c][l[j]])=="number")and 0 or 1)end m[c]=(x<#l and m[c] or nil)c=c+1 end return m end

您可以在线试用Lua,然后复制/粘贴以下代码示例以尝试此提交:

-- The function that does the stuff
function f(m,l)
  c=1 
  while(c<#m)
  do 
    x=0 
    for j=1,#l 
    do 
      x=x+((type(m[c][l[j]])=="number")and 0 or 1)
    end
    m[c]=(x<#l and m[c] or nil)
    c=c+1 
   end 
   return m 
end
-- A function to format matrixes into "readable" strings
function printMatrix(matrix,len)
  s="{"
  for v=1,len
  do
    if matrix[v]~=nil
    then
      s=s.."{"..table.concat(matrix[v],",").."}"..(v<len and",\n "or"")
    end
  end
  s=s.."}"
  print(s)
end

nan="NaN"
-- Datas in, indexed as matrices[testCase][row][column]
matrices={{{7,nan,5,3},{5,4,nan,4},{nan,4,nan,9},{5,7,9,8}},
{{16,nan,3,13},{5,11,nan,8},{nan,7,nan,12},{4,14,-15,1}},
{{nan,nan,nan,nan},{nan,nan,nan,nan},{nan,nan,nan,nan},{nan,nan,nan,nan}}}
indexes={{1,3},{3},{1,2,4}}

-- looping so we can test lots of things at once :)
for i=1,#matrices
do
  print("\ninput: "..table.concat(indexes[i]," "))
  printMatrix(matrices[i],4)
  print("output:")
  printMatrix(f(matrices[i],indexes[i]),4)
end

0

Mathematica,52 51 49 46字节

Delete[#,Extract[#,{;;,#2}]~Position~{NaN..}]&

输入为[矩阵作为列表列表,列向量]


欢迎来到编程难题和代码高尔夫球!:)请更正您的格式并指定输入格式,包括挑战中要求的列索引。
Denker

0

Haskell,39个字节

m#[]=m
m#r=[l|l<-m,any(<1/0)$map(l!!)r]

这使用基于0的索引。用法示例(我sqrt(-1)用于创建NaN):

*Main> [[16,sqrt(-1),3,13], [5,11,sqrt(-1),8], [sqrt(-1),7,sqrt(-1),12], [4,14,-15,1]] # [0,2]
[[16.0,NaN,3.0,13.0],[5.0,11.0,NaN,8.0],[4.0,14.0,-15.0,1.0]]

从列表理解的其他答案中可以看出,这只是一个简单的过滤器。空索引列表的特殊情况将单独捕获。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.