充分利用两个阵列


19

您将获得两个浮点数数组。您的任务是将两个数组的相应元素配对,并获取每对的最大值。但是,如果两个对应的元素相等,则必须取它们的总和。

例如,给定列表[1, 3, 3.2, 2.3][3, 1, 3.2, 2.6],您必须执行以下操作:

  • 一对元件(或zip): [[1, 3], [3, 1], [3.2, 3.2], [2.3, 2.6]]

  • 仔细检查每一对并应用上述过程:[3, 3, 6.4, 2.6]


眼镜

  • 数组/列表将始终具有相等的长度。但是,它们可能是空的。

  • 只要您不滥用这些数字,它们所包含的数字将始终适合您的语言能力。它们可能是正数,零或负数,您必须处理所有类型。

  • 如果它有助于减少字节数,也可以将列表的长度作为输入。

规则


测试用例

Array_1,Array_2->输出

[],[]-> []
[1、2、3],[1、3、2]-> [2、3、3]
[1、3、3.2、2.3],[3、1、3.2、2.6]-> [3、3、6.4、2.6]
[1,2,3,4,5,5,7,8,9,10],[10,9,8,7,6,5,4,3,2,1]-> [10,9, 8、7、6、10、7、8、9、10]
[-3.2,-3.2,-2.4,7,-10.1],[100,-3.2,2.4,-7,-10.1]-> [100,-6.4,2.4,7,-20.2]

您说数字将始终适合“在您的语言的能力范围内”。只要您不“滥用”该数字。仅在不具有浮点数的语言中支持整数才被视为滥用吗?问题是说浮点数吗?但我真的不明白了一个道理,为什么它是漂浮在同样的过程可以在整数做我想在脑高射炮,但脑高射炮来解决这个只支持整数。
小麦向导

@WheatWizard我可以为此例外。继续并发布您的答案,并提到我允许这样做以避免混淆。

Answers:


8

果冻,4个字节

=‘×»

在线尝试!

这使用了与我的APL答案完全相同的方法,除了Jelly具有将数字加一个的内置功能!


讨厌成为剧透对象,但是这些字符中的某些字符难道不是在任何合理的编码中都超过一个字节吗?
Cedric Knight

这使用了果冻代码页
扎卡里

我终于赢了比赛!
扎卡里

2
@ZacharýONE MAN,4 btytes ...这个夏天...你...将会... BE ... JELLY OF HIM ... 评为J代表Jelly
魔术章鱼缸

11

Kotlin,78 75 71 66 65 59字节

这是我的第一次尝试,很酷:D

a.zip(b).map{(a,b)->when{b>a->b;a>b->a;else->a*2}}.toList()

TIO不适用于此解决方案(我也不知道为什么),下面是用于测试的源代码

fun main(args: Array<String>) {
    bestOfTwo(floatArrayOf(), floatArrayOf()).print()
    bestOfTwo(floatArrayOf(0F), floatArrayOf(0F)).print()
    bestOfTwo(floatArrayOf(1F,2F,3F), floatArrayOf(1F,3F,2F)).print()
    bestOfTwo(floatArrayOf(1F,3F,3.2F,2.3F), floatArrayOf(3F,1F,3.2F,2.6F)).print()
    bestOfTwo(floatArrayOf(1F,2F,3F,4F,5F,5F,7F,8F,9F,10F), floatArrayOf(10F,9F,8F,7F,6F,5F,4F,3F,2F,1F)).print()
    bestOfTwo(floatArrayOf(-3.2F,-3.2F,-2.4F,7F,-10.1F), floatArrayOf(100F,-3.2F,2.4F,-7F,-10.1F)).print()
}


fun bestOfTwo(a :FloatArray, b :FloatArray): List<Float> =
    a.zip(b).map{(a,b)->when{b>a->b;a>b->a;else->a*2}}.toList()


fun List<Float>.print() {
    this.forEach { print("$it, ") }; println("")
}

编辑:

-3用“ a * 2”替换“ a + b [i]”

-4通过用“ zip”替换“ mapIndexed”方法(感谢@AnonymousReality Swift解决方案)

-5通过在条件时替换“ Math.max”方法

条件变更时-1

-6通过toList()更改为toFloatArray()


10
欢迎来到PPCG!请不要被低级投票所阻止(这是系统的一些古怪的结果,当新用户的第一条帖子被自动标记为质量,然后他们改善所说的帖子时,会发生系统的怪异!)
Jonathan Allan

2
有史以来最糟糕的“功能” ...顺便说一句,它并不难过。
暴民埃里克(Erik the Outgolfer)'17年

10

Python 2 2,45个字节

我最初的解决方案和@ovs'的混合

lambda*a:map(lambda x,y:max(x,y)*-~(x==y),*a)

在线尝试!

Python 2 2,49个字节

lambda x,y:[max(a,b)*-~(a==b)for a,b in zip(x,y)]

在线尝试!

Python 2 2,46个字节

@ovs建议此方法节省3个字节。

lambda*x:[max(a,b)*-~(a==b)for a,b in zip(*x)]

在线尝试!


怎么样?

首先,我们使用*或配对相应的元素zip()。这使我们可以通过使用地图或列表理解来进一步打高尔夫球。

这个答案中最酷的把戏是这一部分:max(x,y)*-~(x==y)这是如何运作的?-好吧,正如您所知,Python在算术运算中使用布尔值时会将它们自动转换为整数。因此,如果满足条件,则被(x==y)评估为1。但是,如果两个值不相等,它将返回0。然后,按位运算-~将布尔值返回的值增加1,从而得到21max(a,b)给出该对的最大值,并将其*乘以上面返回的值(因此,2仅当它们相等时才乘以,在这种情况下,max()返回两者的值)。

这是基于这样一个事实,即两个相等的数字之和实际上是其中一个都加倍了,并且“滥用” Python的bool类是int的子类。


哇,那真是太快了!

更简单,相同的字节数:lambda*a:map(lambda x,y:(x<=y)*y+(x>=y)*x,*a)
jferard '17

@jferard我事实上,这已经是Luis的解决方案。
Xcoder先生17年

@ Mr.Xcoder糟糕!我没有阅读整个页面……
jferard '17

永远不要说“上面”,因为订货可以改变(我没有看到你上面的解决方案)
扎卡里

8

JavaScript(ES6),53 49 45 43字节

a=>b=>a.map((x,y)=>(y=b[y])>x?y:y<x?x:x+y)
  • 向Xcoder先生借了一个把戏,节省了4个字节。
  • 感谢Arnauld,节省了2个字节。

尝试一下

o.innerText=(f=

a=>b=>a.map((x,y)=>(y=b[y])>x?y:y<x?x:x+y)

)(i.value=[1,3,3.2,2.3])(j.value=[3,1,3.2,2.6]);oninput=_=>o.innerText=f(i.value.split`,`.map(eval))(j.value.split`,`.map(eval))
<input id=i><input id=j><pre id=o>


说明

a=>b=>

匿名函数,使用参数ab,以currying语法(即,使用f(a)(b)

a.map((x,y)=>                      )

映射到第一个数组,将每个元素传递给一个函数,该函数x是当前元素和y当前索引。

(y=b[y])

获取y第二个数组中index处的元素,并将其分配为的新值y

>x?y

检查是否y大于x,如果大于,则返回y

:y<x?x

否则,检查是否y小于x,如果小于,则返回x

:x+y

否则,返回的总和xy。(对于相同的字节数,在这里乘以2 xy2也可以。)


j.value.split`,`.map(eval)还是eval('['+j.value+']')?也x+y看起来更加整洁恕我直言。
尼尔

@Neil:1)我发现前者更容易键入。另外,我的一台机器上有几个Snippet模板;只需.map(eval)将它们粘在上面就容易了。2)同意,将暂时编辑。
毛茸茸的


7

R31 29字节

function(a,b)pmax(a,b)+a*!a-b

pmax 获取两个(或更多)数组的并行最大值(根据需要循环使用较短的数组)。

我在看Luis Mendo的评论时,很明显地我意识到该方法也适用于R。这让我给30个字节,但后来我开始玩弄越来越指数,而不是提高我原来的答案不同的方式,并偶然发现!a-bTRUE,其中a==bFALSE否则,等同于a==b。但是,无论出于何种原因,R都不需要!a-b像在一样加上括号,为a==b我节省了两个字节。

正如JDL在评论中提到的那样,这是有效的,因为!反)的优先级低于-R中的二进制运算符,这很奇怪。

在线尝试!(新版本)

在线尝试!(原版的)


原来,一元“!” 在R中的优先级比二进制“-”低,我认为这是很不寻常的(并且直到读完此答案我才意识到!)
JDL

@JDL是的,在打高尔夫球时,我几乎总是要打开R语法页面,以防出现这种奇怪的怪癖……而且还因为我永远不记得:与算术交互时的优先级。
朱塞佩


6

Dyalog APL,5个字节

⌈×1+=

在线尝试!

怎么样?

  • ,按元素的最大参数
  • ×,逐元素相乘
  • 1+=,1在参数的元素明智相等性上添加

之所以可行,1+=是因为如果数字不相等,则将为,将1其乘以最大值即为最大值。当数字相等时,1+=将返回2,乘以最大值,我们将得到最大值的两倍或最大值加到自身上。


5

果冻,6 个字节

żSṀE?€

双向链接,在每一侧获取一个数字列表,并返回结果列表。

在线尝试!或查看测试套件 *。

怎么样?

żSṀE?€ - Link: list of numbers L, list of numbers R   e.g. [1,3,3.2,2.3], [3,1,3.2,2.6]
ż      - zip - interleave L & R                       [[1,3],[3,1],[3.2,3.2],[2.3,2.6]]
     € - for each pair:
    ?  - { if:
   E   -   ...condition: equal                          0      0       1         0
 S     -   ...then: sum                                               6.4
  Ṁ    -   ...else: maximum                             3      3                2.6
       - }                                    ... ->   [3     ,3     ,6.4      ,2.6]

一个替代方法是此monadic链接采用两个列表的列表,也为6个字节

+»⁼?"/

*我认为我以前从未创建过测试套件页脚几乎是代码字节数的三倍!


出气了!。+1用于问题的几乎逐字解释。
扎卡里

...而且我被发现忘记»矢量化了!
乔纳森·艾伦,

以某种复杂的方式获取最大数组还会做什么呢?
扎卡里

无需任何复杂的定义,Python可以管理-例如max([1,1,0],[1,0,3]) -> [1,1,0](不是[1,1,3])。
乔纳森·艾伦,

那么,基本上是无限基?
扎卡里


4

MATL, 7 bytes

X>tG=s*

Input is a two-row matrix, where each row is one of the arrays.

Try it online!

Explanation

X>   % Implicit input. Maximum of each column
t    % Duplicate
G    % Push input
=    % Is equal? Element-wise with broadcast. Gives a two-row matrix
s    % Sum of each column. Gives a row vector containing 1 and 2
*    % Multiply, element-wise. Implicit display

4

Java 8, 80 69 67 66 65 64 63 bytes

(a,b,l)->{for(;l-->0;)if(a[l]>=b[l])b[l]=a[l]*(a[l]>b[l]?1:2);}

Modifies the second input-array instead or returning a new float-array to save bytes.

-11 bytes by taking the length as additional integer-input, which is allowed according to the challenge rules.
-5 bytes thanks to @OliverGrégoire (one byte at a time.. xD)
-1 byte indirectly thanks to @Shaggy's JS answer, by using a[l]*2 instead of a[l]+b[l].

Explanation:

Try it here.

(a,b,l)->{          // Method with 2 float-array and integer parameters and no return-type
  for(;l-->0;)      //  Loop over the array
    if(a[l]>=b[l])  //   If the current value in `a` is larger or equal to `b`:
      b[l]=         //   Modify the second input-array:
       a[l]*        //    Use `a` multiplied by:
        (a[l]>b[l]? //     If the current value in `a` is larger than `b`:
          1         //      Multiply by 1
         :          //     Else (`a` is smaller of equal to `b`):
          2)        //      Multiply by 2
                    //  End of loop (implicit / single-line body)
}                   // End of method

2
"If it helps you reduce your byte count, you may also take the length of the lists as input." It will definitely reduce your byte-count ;)
Olivier Grégoire

1
Also, 2 bytes shorter: a->b->l->{float A,B;for(;l-->0;b[l]=(A=a[l])<B?B:A>B?A:A+B)B=b[l];}
Olivier Grégoire

And you can save one more byte by putting float A, B in the for initialization.
Olivier Grégoire

1
Or this: (a,b,l)->{for(;l-->0;)if(a[l]>=b[l])b[l]=a[l]*(a[l]>b[l]?1:2);} (63 bytes)
Olivier Grégoire

3
@OlivierGrégoire Lol.. with golfing every byte helps, but that doesn't mean you need to golf it one byte at a time. ;p
Kevin Cruijssen


3

05AB1E, 9 8 7 bytes

Saved a byte as Erik the Outgolfer pointed out that a list of lists is valid input.

øεMsËi·

Try it online!

Explanation

ø          # zip the lists
 ε         # apply to each pair
  M        # get max
   s       # swap the top 2 elements on the stack
    Ëi     # if all elements are equal
      ·    # double the max

Wow, that was really fast!

You can save a byte by removing the and inputting as a pair of a list and a list.
Erik the Outgolfer

@EriktheOutgolfer: True. I assumed we weren't allowed to, but I see that the challenge does specify standard I/O rules. Thanks for notifying :)
Emigna

1
@Emigna Tip: don't make rules out of your mind ;)
Erik the Outgolfer

1
@EriktheOutgolfer: Yeah I really need to stop doing that. Especially rules which make my programs longer ;)
Emigna


3

J, 7 bytes

>.`+@.=

Try it online!

Takes one list as the left argument and the other as the right.

Luckily, equality is a rank zero operation.

Explanation

>.`+@.=
      =  Compare equality pairwise
    @.   If equal
   +       Sum
>.       (Else) take greater value

@. isn't really an if statement, but in this case it functions as one (it indexes into the gerund >.`+ based on the result of its right argument and applies that to the input).


Nice job, I know I couldn't do this, even though you have beenoutgolfed by my translation of my APL. >_<
Zacharý

J really shines here
Jonah

@Zacharý rats, well-golfed nonetheless.
cole


3

TI-Basic, 23 21 bytes

Prompt A,B
(ʟA=ʟB)ʟA+max(ʟA,ʟB

Too bad lists take up two bytes each...


You can save two bytes by prompting for X and Y, then using ʟX and ʟY to access them, i.e. "Prompt X,Y:ʟX(ʟX=ʟY)+max(ʟ1,ʟ2".
Scott Milner

Also, this is currently invalid, since L1(L1=L2) attempts to get the element of L1 at a list, which throws an error. To fix that, swap the order, i.e. (L1=L2)L1.
Scott Milner

@ScottMilner Thanks for pointing both of those out.
Timtech




2

Common Lisp, 60 59 bytes

(mapcar(lambda(x y)(*(max x y)(if(= x y)2 1)))(read)(read))

Try it online!

-1 byte thanks to @Zacharý!


59 bytes: (mapcar(lambda(x y)(*(max x y)(if(= x y)2 1)))(read)(read)).
Zacharý

You're welcome, I don't know lisp that well, I just translated my other answers into Lisp which ended up saving a byte.
Zacharý

2

Python with numpy, 28 bytes

lambda a,b:a*(a>=b)+b*(b>=a)

Assumes input is given as two numpy arrays.


If we are using numpy then here is my worse solution: lambda a,b:n.fmax(a,b)*((a==b)+1)
Erich

@Erich I like the idea, but to do that I would need to import numpy as n. I get away without it here because it's implicit in the input.

I guess i'm a bit shaky on the explicit byte counting, often python answers are simply lambdas, when an actual implementation of an answer would require assigning it to something. for this reason I wonder if it is allowable to get away with an implicit import statement as well?
Erich

@Erich In general, you can only refer to a variable n if you've defined n in your code, so imports must be explicit. By default, we allow functions or full programs as answers, which includes anonymous functions.

1
Well, this only needs input as numpy arrays, rather than importing numpy. But does this even work without using return?
Zacharý

2

C# (.NET Core), using Linq 47+18=65 bytes

x=>y=>x.Zip(y,(a,b)=>a>b?a:b>a?b:b+a).ToArray()

Try it online!

C# (.NET Core), 82 bytes

x=>y=>l=>{for(int i=0;i<l;i++)x[i]=x[i]>y[i]?x[i]:y[i]>x[i]?y[i]:y[i]*2;return x;}

Try it online!


You can drop the LINQ answer by a few bytes by changing namespace System.LINQ to using System.LINQ
jkelm

@jkelm yeah, I've been wondering if the 'using System;` is to be included or not like that, I guess not. I'll clean it up
Dennis.Verweij

System.Linq is included in the "Visual C# Interactive Compiler". I am not totally sure about returning Array vs IList vs IEnumerable, but if all are eligible then you can get the byte count to 37 - tio.run/##Sy7WTS7O/…
dana


1

Swift 3, 81 79 Bytes

func n(a:[Double],b:[Double]){for(x,y)in zip(a,b){print((x==y) ?x+y:max(x,y))}}

Swift has an interesting property in that an Int isn't directly castable to a Double, so you have to specify any arrays as being arrays of Doubles before passing them to the function.

(e.g.) var k:[Double] = [1,2,3,4,5,5,7,8,9,10]

Edit: -2 bytes thanks to @EriktheOutgolfer


Do you need spaces around (x,y) and before ??
Erik the Outgolfer

@EriktheOutgolfer The one before ? is needed because Swift would treat them as optional types instead of ternaries (which they aren't). The others aren't. Apart from that, this can be drastically golfed.

@EriktheOutgolfer - TheIOSCoder has already answered you partly, but you're right, you don't need the ones in the for loop, interesting!
AnonymousReality

73 bytes: func n(a:[Float],b:[Float]){print(zip(a,b).map{$0==$1 ?2*$0:max($0,$1)})} (the float inaccuracies need not to be handled by default)
Mr. Xcoder

Or 74 bytes: func n(a:[Float],b:[Float]){print(zip(a,b).map{($0==$1 ?2:1)*max($0,$1)})}
Mr. Xcoder

1

C, 76 75 bytes

Thanks to @Kevin Cruijssen for saving a byte!

f(a,b,n)float*a,*b;{for(;n--;++a,++b)printf("%f ",*a>*b?*a:*b>*a?*b:*a*2);}

Try it online!


1

Japt, 13 bytes

íV,È¥Y Ä *XwY

Try it online! with the -Q flag to format the output array.


Nicely done. I made 2 attempts at this earlier with both coming out at 17 bytes. I'd forgotten í could take a function as a second argument.
Shaggy

1

Rust, 107 97 bytes

|a:V,b:V|a.iter().zip(b).map(|(&x,y)|if x==y{x+y}else{x.max(y)}).collect::<V>();
type V=Vec<f32>;

Try it online!

Saved 8 bytes thanks to @mgc


1
I guess you can save 8 bytes by using type inference on the collected Vec and by using the max method of f32s: |a:Vec<f32>,b:Vec<f32>|a.iter().zip(b).map(|(&x,y)|if x==y{x+y}else{x.max(y)}).collect::<Vec<_>>();
mgc

1
@mgc Thanks! Type inference was a good idea, but in this case type alias is even shorter.
jferard

1

Swift 4, 41 bytes

{zip($0,$1).map{$0==$1 ?2*$0:max($0,$1)}}

Test cases:

let f: ([Float], [Float]) -> [Float]
    = {zip($0,$1).map{$0==$1 ?2*$0:max($0,$1)}}

let testcases: [(inputA: [Float], inputB: [Float], expected: [Float])] = [
    (
        inputA: [],
        inputB: [],
        expected: []
    ),
    (
        inputA: [1, 2, 3],
        inputB: [1, 3, 2],
        expected: [2, 3, 3]
    ),
    (
        inputA: [1, 3, 3.2, 2.3],
        inputB:  [3, 1, 3.2, 2.6],
        expected: [3, 3, 6.4, 2.6]
    ),
    (
        inputA: [1,2,3,4,5,5,7,8,9,10],
        inputB:  [10,9,8,7,6,5,4,3,2,1],
        expected: [10, 9, 8, 7, 6, 10, 7, 8, 9, 10]
    ),
    (
        inputA: [-3.2, -3.2, -2.4, 7, -10.1],
        inputB:  [100, -3.2, 2.4, -7, -10.1],
        expected: [100, -6.4, 2.4, 7, -20.2]
    ),
]

for (caseNumber, testcase) in testcases.enumerated() {
    let actual = f(testcase.inputA, testcase.inputB)
    assert(actual == testcase.expected,
        "Testcase #\(caseNumber) \((testcase.inputA, testcase.inputB)) failed. Got \(actual), but expected \(testcase.expected)!")
    print("Testcase #\(caseNumber) passed!")
}
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.