修剪数组!


27

给定一个整数数组和两个数字作为输入,请删除由数字指定的一定数量的第一个和最后一个元素。输入可以按照您想要的任何顺序。

您应该删除前x个元素,其中x是第一个数字输入,还应该删除最后y个元素,其中y是第二个数字输入。

保证结果数组的长度至少为2。

例子:

[1 2 3 4 5 6] 2 1 -> [3 4 5]
[6 2 4 3 5 1 3] 5 0 -> [1 3]
[1 2] 0 0 -> [1 2]

2
确切地说,从数组中“删除”值,尤其是从末尾删除它们意味着什么?在像C这样的语言中,数组只是指向第一个元素的指针和一个长度,我们是否可以更改长度以截断数组?这通常是在现实世界中进行的编程,但是对我而言挑战并不明确。
科迪·格雷

@CodyGray从数组中删除值应该是它的样子,但不一定是幕后发生的事情。
Okx

4
“看起来”是什么意思?数组不用 - 一切都在幕后!
科迪·格雷


2
@Okx Nope,那是非常有问题的车,我建议添加排行榜。
暴民埃里克(Erik the Outgolfer)'17年

Answers:


16

Haskell,55 39 33 29字节

感谢Laikoni,节省了16个字节

多亏了Laikoni,节省了6个字节

多亏了Laikoni,节省了4个字节

当然可以改进,但是作为初学者,请尽我最大的努力。

r=(reverse.).drop
a#b=r b.r a

用法

(5#0) [6,5,4,3,2,1,3]

在线尝试!


5
欢迎来到PPCG,尤其是Haskell高尔夫!目的是使用尽可能少的字节,因此您可以例如删除大多数空格并缩短xs
Laikoni

@Laikoni啊,谢谢!编辑后,如果没有匿名函数并且对函数使用applicative(无法确定其工作原理),我将无法再走近一步。
亨利

现在看起来不错!:)如果您更改f x a bf a b x,则只需删除xf a b=reverse.drop b.reverse.drop a.。
Laikoni

1
@Laikoni Wow,有趣的中缀技巧。再次感谢!我能够将其缩短为33个字节,但尝试执行的却a#b=let r=reverse in r.drop b.r.drop a是38个字节。还是允许我们在此函数之外声明一个函数?
亨利

1
@Laikoni感谢您的介绍,非常有帮助。刚刚在今天找到了这个网站,但是绝对希望在这里玩更多!
亨利


6

Mathematica,17个字节

#[[#2+1;;-#3-1]]&

输入

[{1、2、3、4、5、6},2、1]


很好用;;!我设法与您配合Drop@##2~Drop~-#&(如果我们按怪异的顺序输入1, {1,2,3,4,5,6}, 2),但没有更好的选择。
格雷格·马丁

6

Python28岁 26字节

-2个字节感谢@Rod

lambda a,n,m:a[n:len(a)-m]

在线尝试!


保存6 ...lambda a,n,m:a[n:~m]
亚伦

@Aaron这样会过多地删除一项。
ovs

我的坏..这是一种常见的伎俩我有时使用,并没有完全检查对挑战的需求..
阿伦

@Aaron切片的运算符优先级高于+,因此应用于[0]。您将需要使用方括号:(a+[0])[n:~m]
ovs

是的,后来才意识到。.我正在努力使我的想法行得通
亚伦

6

C#(.NET Core)55 54字节

using System.Linq;(a,x,y)=>a.Skip(x).Take(a.Count-x-y)

在线尝试!

使用List<int>作为输入。

  • 感谢TheLethalCoder,节省了1个字节!

1
我正要回答这个+1。但是,您可以通过将a List作为输入来保存字节,因此可以使用Count代替Length
TheLethalCoder

我想出了一个解决方案,该解决方案的使用Where时间仅比我也很满意的方法稍长:)
TheLethalCoder

您不需要增加using System.Linq;字节数:)
Stefan

@Stefan我需要计算using我在答案中添加的每一个内容Skip以及Take需要的方法和数量using
查理

嗯。好的。在其他一些挑战上,我被告知那些不必要的用法。
Stefan

5

Perl 5,21个字节

19个字节的代码+ -ap标志。

$_="@F[<>..$#F-<>]"

在线尝试!

用于-a在内部自动拆分输入@F,然后仅根据其他输入保留其一部分:从索引<>(第二个输入)到索引$#F-<>(数组大小减去第三个输入)。并$_通过-pflag 隐式打印。


5

Rust,29个字节

|n,i,j|&n[i..<[_]>::len(n)-j]

调用如下:

let a = &[1, 2, 3, 4, 5, 6];
let f = |n,i,j|&n[i..<[_]>::len(n)-j];
f(a, 2, 1)

我与借位检查器进行了很多有趣的战斗,弄清楚最短的方法是什么,以便推断出返回切片的生命周期。它在闭包周围的行为有些不稳定,因为它将推断生存期,但前提是您实际上没有将参数声明为引用类型。不幸的是,这与要求在签名中定义参数类型冲突,因为n.len方法调用需要知道其操作的类型。

我尝试解决此问题的其他方法:

fn f<T>(n:&[T],i:usize,j:usize)->&[T]{&n[i..n.len()-j]}     // full function, elided lifetimes
let f:for<'a>fn(&'a[_],_,_)->&'a[_]=|n,i,j|&n[i..n.len()-j] // type annotation only for lifetimes. Currently in beta.
|n:&[_],i,j|n[i..n.len()-j].to_vec()                        // returns an owned value
|n,i,j|&(n as&[_])[i..(n as&[_]).len()-j]                   // casts to determine the type
|n,i,j|&(n:&[_])[i..n.len()-j]                              // type ascription (unstable feature)
|n,i,j|{let b:&[_]=n;&b[i..b.len()-j]}                      // re-assignment to declare the type


4

C#,62个字节

using System.Linq;(l,x,y)=>l.Where((n,i)=>i>=x&i<=l.Count-y-1)

接受List<int>作为输入并返回IEnumerable<int>


这也适用于64个字节:

using System.Linq;(l,x,y)=>l.Skip(x).Reverse().Skip(y).Reverse()

4

TIS-100,413个 405字节

472个周期,5个节点,35行代码

m4,6
@0
MOV 0 ANY
S:MOV UP ACC
JEZ A
MOV ACC ANY
JMP S
A:MOV RIGHT ACC
L:JEZ B
MOV DOWN NIL
SUB 1
JMP L
B:MOV 0 RIGHT
MOV RIGHT NIL
@1
MOV RIGHT LEFT
MOV LEFT DOWN
MOV RIGHT DOWN
MOV DOWN LEFT
@2
MOV UP ACC
MOV UP LEFT
MOV ACC LEFT
@4
MOV 0 RIGHT
MOV UP NIL
S:MOV LEFT ACC
JEZ A
MOV ACC RIGHT
JMP S
A:MOV UP ACC
L:JEZ B
MOV RIGHT NIL
SUB 1
JMP L
B:MOV 0 UP
K:MOV RIGHT ACC
MOV ACC DOWN
JNZ K
@7
MOV UP ANY

顶部的m4,6不是代码的一部分,而是表示内存模块的位置。

enter image description here

通过将其粘贴到游戏中来自己玩此关卡:


function get_name()
    return "ARRAY TRIMMER"
end
function get_description()
    return { "RECIEVE AN ARRAY FROM IN.A", "RECIEVE TWO VALUES A THEN B FROM IN.T", "REMOVE THE FIRST A TERMS AND LAST B TERMS FROM IN.A", "ARRAYS ARE 0 TERMINATED" }
end

function get_streams()
    input = {}
    trim = {}
    output = {}

  arrayLengths = {}

    a = math.random(1,5) - 3

    b = math.random(1,7) - 4

    arrayLengths[1] = 9+a
    arrayLengths[2] = 9+b
    arrayLengths[3] = 8-a
    arrayLengths[4] = 9-b

    s = 0

    trimIndex = 1

  for i = 1,4 do
      for k = 1,arrayLengths[i] do
          x = math.random(1,999)
      input[k+s] = x
            output[k+s] = x
        end

        input[s + arrayLengths[i] + 1]= 0
        output[s + arrayLengths[i] + 1]= 0

        a = math.random(0,3)
        b = math.random(0,arrayLengths[i]-a)

        trim[trimIndex] = a
        trim[trimIndex+1] = b

        trimIndex = trimIndex + 2

    s = s + arrayLengths[i] + 1
    end

    s = 1
    trimIndex = 1

    for i = 1,4 do

      for i = s,s+trim[trimIndex]-1 do
          output[i]=-99
        end

        for i = s + arrayLengths[i] - trim[trimIndex+1], s + arrayLengths[i]-1 do
      output[i]=-99
        end

  trimIndex = trimIndex +2
  s = s + arrayLengths[i] + 1
    end

    trimmedOut = {}
    for i = 1,39 do
            if(output[i] ~= -99) then
                    table.insert(trimmedOut, output[i])
            end
    end

    return {
        { STREAM_INPUT, "IN.A", 0, input },
        { STREAM_INPUT, "IN.T", 2, trim },
        { STREAM_OUTPUT, "OUT.A", 1, trimmedOut },
    }
end
function get_layout()
    return {
        TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,
        TILE_MEMORY,    TILE_COMPUTE,    TILE_MEMORY,   TILE_COMPUTE,
        TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,
    }
end

所以我想这也算是一个不错的答案...


您现在可以在线尝试!注意:我必须做得很聪明,并且将代码文件的顶部用作输入的一个来源,因为TIO当前仅提供一个输入文件。
Phlarx

4

MATL,6个字节

QJi-h)

在线尝试!

输入如下:1)从头开始修剪的元素数量;2)从末端修剪的元素数量;3)数组。说明

Q   % Implicit input (1). Increment by 1, since MATL indexing is 1-based.
Ji- % Complex 1i minus real input (2). In MATL, the end of the array is given by `1i`.
h   % Concatenate indices to get range-based indexing 1+(1):end-(2).
)   % Index into (implicitly taken) input array. Implicit display.


3

JavaScript(ES6),27个字节

(a,n,m)=>a.slice(n,-m||1/m)

负的第二个参数可slice停止m从末尾开始切片,但是当m为零时,我们必须传递一个占位符(Infinity在这里,尽管(a,n,m,o)=>a.slice(n,-m||o)也可以)。


3

R32 31 30字节

-1字节感谢Rift

-1个字节感谢Jarko Dubbeldam

pryr::f(n[(1+l):(sum(n|1)-r)])

评估为匿名函数:

function (l, n, r) 
    n[(1 + l):(sum(n|1) - r)]

1+l由于R具有基于1的索引,因此是必需的。sum(n|1)等效于,length(n)但短了一个字节。

在线尝试!


1
拯救1个字节pryr::f(n[(1+l):(length(n)-r)])
裂谷

1
总和(n | 1)短于length(n)
JAD

@JarkoDubbeldam很好,谢谢。
朱塞佩

3

MATL,10字节

tniQwi-&:)

在线尝试!

说明:

它只有11个字节,有点长,但是我正在详细写出来,我自己也要学习。

---- Input ----
[1 2 3 4 5 6]
2
1
----- Code ----
           % Implicit first input
t          % Duplicate input.
           % Stack: [1 2 3 4 5 6], [1 2 3 4 5 6]
 n         % Number of elements
           % Stack: [1 2 3 4 5 6], 6
  i        % Second input
           % Stack: [1 2 3 4 5 6], 6, 2
   Q       % Increment: [1 2 3 4 5 6], 6, 3
    w      % Swap last two elements
           % Stack: [1 2 3 4 5 6], 3, 6
     i     % Third input
           % Stack: [1 2 3 4 5 6], 3, 6, 1
      -    % Subtract
           % Stack: [1 2 3 4 5 6], 3, 5
       &:  % Range with two input arguments, [3 4 5]
           % Stack: [1 2 3 4 5 6], [3 4 5]
         ) % Use as index
           % Stack: [3 4 5]
           % Implicit display

您忘记了基于末端的索引;)
Sanchises

(仍然要投票-我认为打高尔夫球很好,考虑到您使用的方法,可以解释一下)
-Sanchises

不,我没有忘记它!我尝试过,但是我没有弄清楚如何使其工作(我真的尝试过)。我得出的结论是J,像这样使用时,不可能从中减去某些东西。我怀疑自己错了,我一辈子都想不起来...感谢您的回答,我非常是一名MATL新手...
Stewie Griffin

别担心,我仍然在学习很多东西,例如输入的顺序)以及更加令人( 发抖的 ……
Sanchises

@Sanchises很晚才发表评论,但是我很高兴发现输入顺序(混乱的不仅是我。:)我每次都背诵“ ddi”(=手册中的“ destination,data,indexs”),有时还是会出错。
sundar-恢复莫妮卡

3

C ++,96 95字节

感谢@Tas节省了一个字节!

#import<list>
int f(std::list<int>&l,int x,int y){for(l.resize(l.size()-y);x--;)l.pop_front();}

在线尝试!

C ++(MinGW),91字节

#import<list>
f(std::list<int>&l,int x,int y){for(l.resize(l.size()-y);x--;)l.pop_front();}

你是说#include<list>吗 您可以通过剃光一个字节int f。编译器将不允许函数返回,但会对其进行警告
Tas

是的,谢谢,int f它将适用于大多数编译器,我将对其进行编辑。在MinGW上,甚至完全省略了函数的类型。是的,#include<list>这是一种包含标头的符合标准的方法,但#import<list>至少应在GCC,MinGW和MSVC上工作,因此也应该很好。
Steadybox

2

APL(Dyalog)8 7字节

⌽⎕↓⌽⎕↓⎕

在线尝试!

这将数组作为第一个输入,然后是两个数字。

说明

            from the input array
⎕↓           drop the first input elements
            reverse the array
⎕↓           drop first input elements
            reverse again to go back to the original array

Alternative 7 byte solution: ⎕↓⎕↓⍨-⎕
Adám


2

Brain-Flak, 60 bytes

(()()){({}<{({}<{}>[()])}{}([]){{}({}<>)<>([])}{}<>>[()])}{}

Try it online!

Input is in this format:

x

a
r
r
a
y

y

Where x is the number to take from the front, y is the number to take from the back, and the array is just however many numbers you want, separated by newlines. Here are my first two (longer) attempts:

({}<>)<>{({}<{}>[()])}([])<>({}<><{{}({}<>)<>([])}{}><>){({}<{}>[()])}{}([]){{}({}<>)<>([])}<>{}
{({}<{}>[()])}{}([]){{}({}<>)<>([])}{}<>{({}<{}>[()])}{}([]){{}({}<>)<>([])}<>

And here is an explanation:

#Two times:
(()()){({}<

    #Remove *n* numbers from the top of the stack
    {({}<{}>[()])}{}

    #Reverse the whole stack
    ([]){{}({}<>)<>([])}{}<>

>)[()]}{}

1
Nice to see a turing tarpit solution every now and then.
Okx

2

APL (Dyalog), 5 bytes

(⌽↓)/

Try it online!


Input format is y x A

Explanation

/ is Reduce, which inserts the function to the left between each pair of elements of the argument

(⌽↓) is a function train equivalent to {⌽⍺↓⍵}, which removes the first elements of the array and then reverses the array. ( is the left argument and is the right argument)

Thus, (⌽↓)/y x A is equivalent to ⌽y↓⌽x↓A, which is what is needed.


2

Java 8, 82 bytes

a->n->m->{int l=a.length-m-n,r[]=new int[l];System.arraycopy(a,n,r,0,l);return r;}

Try it here.

Alternative with same (82) byte-count using a loop:

(a,n,m)->{int l=a.length-m,r[]=new int[l-n],i=0;for(;n<l;r[i++]=a[n++]);return r;}

Try it here.

Explanation:

a->n->m->{                      // Method with integer-array and two integer parameters and integer-array return-type
  int l=a.length-m-n,           //  Length of the array minus the two integers
      r[]=new int[l];           //  Result integer-array
  System.arraycopy(a,n,r,0,l);  //  Java built-in to copy part of an array to another array
  return r;                     //  Return result-String
}                               // End of method

System.arraycopy:

arraycopy(Object src, int srcPos, Object dest, int destPos, int length):

The java.lang.System.arraycopy() method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument.

The components at positions srcPos through srcPos + length - 1 in the source array are copied into positions destPos through destPos + length - 1, respectively, of the destination array.


Can you save bytes by not using currying?
TheLethalCoder

@TheLethalCoder No, in this case not. (a,n,m)-> has the same byte-count as a->n->m->. Although you're right I could have just used a regular call instead of currying. I'm kinda used of using currying when I have two (or more) parameters.. I've already made the mistake of using currying when I have four parameters a few times..
Kevin Cruijssen

Ahh you're right I miscounted the bytes and I've done that as well currying is definitely a go to now!
TheLethalCoder

No TIO link? --
totallyhuman

2
Sorry, can't let that pass. I posted my own answer because... there's a built-in (ok, not exactly, but nearly)! :o
Olivier Grégoire


2

Kotlin, 30 bytes

{a,s,e->a.drop(s).dropLast(e)}

Try it online!

Takes List<Int> as input and drops from begin and then from end.


1
I have not access to try it online. Can you add a caller code? how compile lambda without type definitions in Kotlin? Thanks.
mazzy

1
@mazzy it could probably be a hack, but you can specify types in variable type definition as val f: (List<Int>, Int, Int) -> List<Int>
YGolybev

Got it! Nice. I don't know if this is valid in CodeGolf.
mazzy

2

Brachylog, 11 10 bytes

kb₍B&t;Bk₍

Try it online!

Takes input as [x, A, y] where A is the array to trim.

(-1 byte thanks to @Fatalize.)


You can shorten it by 1 byte as such: kb₍B&t;Bk₍. , does append (see the result of this partial program), it doesn't act like . Also do not try to copy things from old (2016-early 2017) Brachylog answers because it was the first version of the language, and programs are not retrocompatible (in particular, , in Brachylog v1 is now in Brachylog v2)
Fatalize

@Fatalize Thanks, updated. So , did append in the previous version, but it just didn't matter in this case because there was a t after it anyway - lucky coincidence. And yeah, I realized the version differences after I posted this, I was still figuring things out and bumbling around at this stage. :)
sundar - Reinstate Monica


1

Pyth, 5 bytes

>E<QE

Try it here

Takes the arguments in the opposite order. < and > in Pyth trim based on argument order. For example, <Q5 will trim off all values in the input after the fifth one.



1

CJam, 8 bytes

{_,@-<>}

Anonymous block that takes the inputs from the stack in the order x, y, array, and replaces them by the output array.

Try it online!

Explanation

Consider inputs 2, 1, [10 20 30 40 50 60].

{      }    e# Block
            e# STACK: 2, 1, [10 20 30 40 50 60]
 _          e# Duplicate
            e# STACK: 2, 1, [10 20 30 40 50 60], [10 20 30 40 50 60]
  ,         e# Length
            e# STACK: 2, 1, [10 20 30 40 50 60], 6
   @        e# Rotate
            e# STACK: 2, [10 20 30 40 50 60], 6, 1
    -       e# Subtract
            e# STACK: 2, [10 20 30 40 50 60], 5
     <      e# Slice before
            e# STACK: 2, [10 20 30 40 50]
      >     e# Slice after
            e# STACK: [30 40 50]

1
Good point, then just for fun, here is an alternative 8-byte solution :) tio.run/##S85KzP1vxGXIFW1ooGBkoGBsoGBioGBqoGBmEPu/Olg7ps7GrvZ/…
Martin Ender

1

q/kdb, 12 bytes

Solution:

{(0-z)_y _x}

Example:

q){(0-z)_y _x}[1 2 3 4 5 6;2;1]
3 4 5
q){(0-z)_y _x}[6 2 4 3 5 1 3;5;0]
1 3
q){(0-z)_y _x}[1 2;0;0]
1 2

Explanation:

{          } / lambda function
          x  / input array
       y _   / drop y elements from .. (takes from start)
 (0-z)       / negative z ()
      _      / drop -z elements from ... (takes from end)

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.