交换两个给定的索引


31

给定一个正整数数组和两个不同的有效索引,则返回该数组,其中对应于两个索引的两个元素被交换。

您可以选择使用0索引或1索引,但是下面的测试用例将使用0索引。

array        m n output
[1,2,3,4]    0 1 [2,1,3,4]
[5,8,9]      0 2 [9,8,5]
[11,13,15,3] 1 2 [11,15,13,3]
[11,13,15,3] 2 1 [11,15,13,3]
[11,15,15,3] 2 1 [11,15,15,3]

这是。以字节为单位的最短答案将获胜。有标准漏洞



1
呵呵,这很可能是许多高尔夫语言难以应付的任务,但是大多数实用语言都容易实现。(具有可变元素的列表对于打高尔夫球的语言来说并不常见。)如果是这种情况,那将非常有趣。(不过,高尔夫语言可能仍然会取胜,因为它们麻烦了,他们可以使用更复杂的算法来摆脱。)

7
惊奇的是这可能不是骗人的,但是这个挑战实际上是有创造力的,因为对于许多高尔夫语言来说,这是一个真正的挑战。
暴民埃里克(Erik the Outgolfer)'17年

@LeakyNun我过去有过类似的投票(甚至删除选票),不必为此担心太多……
Outgolfer的Erik

可以m并将n其视为数组吗?
Okx

Answers:


17

C/ C ++53 50 39个字节

f(a,m,n)int*a;{a[m]^=a[n]^=a[m]^=a[n];}

在线尝试

@Dennis节省了11个字节


10

操作Flashpoint脚本语言,98 95字节

f={t=_this;a=t select 0;b=+a;m=t select 1;n=t select 2;a set[m,b select n];a set[n,b select m]}

直接修改数组。

说明:

t=_this;                   // Give a shorter name for the array of arguments.

a=t select 0;              // Let 'a' be a pointer to the array that we modify.
                           // (The language doesn't have a concept of pointers really,
                           // yet its array variables are pointers to the actual array.)

b=+a;                      // Make a copy of the original array and save a pointer to it
                           // in the variable 'b'. This saves a few bytes later.

m=t select 1;              // Read the index arguments from the input array and save them
n=t select 2;              // to their respective variables.

a set[m,b select n];       // Do the swapping by reading the values from the copy and
a set[n,b select m]        // writing them to the original array. The last semicolon can
                           // be omitted because there are no more statements following 
                           // the last statement.

致电:

array = [1,2,3,4];
str = format["%1", array];
[array, 0, 1] call f;
hint format["%1\n%2", str, array];

输出:

enter image description here


7

的JavaScript ES6,36 32个字节

瞧,妈,没有临时变量!

(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]

试试吧

输入以逗号分隔的元素列表,a以及m&的2个整数n

f=
(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]
oninput=_=>o.innerText=(f(b=i.value.split`,`,+j.value,+k.value),b);o.innerText=(f(b=(i.value="5,8,9").split`,`,j.value=0,k.value=2),b)
*{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}#j,#k{width:50px;}
<label for=i>a: </label><input id=i><label for=j>m: </label><input id=j type=number><label for=k>n: </label><input id=k type=number><pre id=o>


2
这些指令修改了数组,这意味着您不可以返回数组,这将节省一些字节。
尼尔

@Neil:您是说要使用(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]?那只会输出2个交换的元素,而不输出数组的其余部分(例如[5,8,9],0,2-> [9,5])。
毛茸茸的

@Neil:是的,这就是为什么我们需要a最后给我们提供完整的,经过修改的数组的原因。还是我完全想念您要说的话?
毛茸茸的

@Neil:嗯...好吧,我想我明白您现在正在得到什么(对不起,今天尝试同时做太多事情)。谢谢你的提示。是否对此有共识,如果可以,在我自己进行搜索之前,您是否有一个方便的链接?
毛茸茸的



5

果冻,7个字节

Ṛ,ḷyJ}ị

在线尝试!

怎么运行的

Ṛ,ḷyJ}ị  Main link. Left argument: [i, j]. Right argument: A (array)

Ṛ        Reverse; yield [j, i].
  ḷ      Left; yield [i, j].
 ,       Pair; yield [[j, i], [i, j]].
    J}   Indices right; yield all indices of A.
   y     Transliterate; replace j with i and i with j.
      ị  Index into A.

tww包装程序几乎与该程序一样长...
Leaky Nun

我从来不知道y
Leaky Nun

我知道y,但没有想到在这里使用它。这是一个非常聪明的答案。

这让我开始思考...是Jelly有效的Jelly代码吗?
M.Herzkamp

@ M.Herzkamp是的。我怀疑它是否特别有用。
丹尼斯,


4

MATL7 6字节

yyP)w(

索引基于1。

在线尝试!

说明

考虑输入[11 13 15 3][2 3]

yy   % Take two inputs implicitly. Duplicate them
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [2 3]
P    % Flip
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [3 2]
)    % Reference indexing (pick indexed entries)
     % STACK: [11 13 15 3], [2 3], [15 13]
w    % Swap
     % STACK: [11 13 15 3], [15 13], [2 3]
(    % Assignment indexing (write values into indexed entries). Implicitly display
     % STACK: [11 15 13 3]



3

的Javascript ES6,36个 34字节

(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)
  • -2字节,因为该函数正在更改数组。无需返回数组。感谢@Neil

演示版


1
这些指令修改了数组,这意味着您不可以返回数组,这将节省一些字节。
尼尔


2

Java 8,48字节

(a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;return a;}

输入:

int[] a
int b
int c

如何在Java中使用三个参数处理lambda?
Leaky Nun

1
这些指令修改了数组,这意味着您不可以返回数组,这将节省一些字节。
尼尔

1
@LeakyNun我不是Okx,但这是一个使用Okx当前答案和自定义界面的“ 立即尝试”示例
凯文·克鲁伊森

1
基于Carlos Alejo令人惊叹的C#答案(在@Neil的帮助下),您可以通过消除临时变量来缩短它的长度:(a,b,c)->a[b]+=a[c]-(a[c]=a[b])31个字节
Kevin Cruijssen

1
咳嗽咳嗽 Collections::swap17个字节 ...至少假设这可以应付这个挑战...
苏格拉底凤凰城,


2

八度,28字节

@(a,n){a(n)=a(flip(n)),a}{2}

在线尝试!

实际上对此感到非常满意:)

接受以下格式的输入:f([1,2,3,4],[1,2])1索引。

说明:

@(a,n)                         % Anonymous function that takes two 1-dimensional
                               % arrays as input
      {               , }      % Create a cell with two elements
       a(n)=a(flip(n))         % One element are the two number at indices given by
                               % the second input array. This will be a 1x2 array
      {a(n)=a(flip(n)),a}      % Place those two in a cell together with the entire array a
                               % a is now updated, thanks to Octave's inline assignment
      {a(n)=a(flip(n)),a}{2}   % Return the second element

2

水母,7个字节

p
ZRi
i

取得一个列表和一对索引。 在线尝试!

说明

水母恰好具有“在索引处修改项目”功能Z,该功能正是我们所需要的。这两个i从STDIN获取输入。 Z将第二个输入,反转函数R和列表作为参数。然后Z执行修改,并p打印结果。


2

R,38个字节

function(x,a,b){x[c(a,b)]=x[c(b,a)];x}

感觉相当长,但我无法将其缩短。可悲的是它需要显式的返回通过x,要求{}各地函数体。pryr::f()无法识别需要xas函数参数,因此无法正常工作:/。


我认为function(x,i)replace(x,i,rev(i))即使使用pryr语法也可以。
朱塞佩

@Giuseppe啊,我正在寻找一个方便的函数来执行交换,但是搜索的术语错误。随意将其发布为自己的答案。
JAD

@Giuseppe我认为您需要做replace(x,i,x[rev(i)]),否则您将放置索引而不是它们的值。
JAD

2

深圳I / O,735字节

23¥,810电源,48行代码

[traces] 
......................
......................
......................
......................
......................
......................
.14.14.14.............
.94.14.14.............
.A........1C..........
.3554..95556..........
.9554.16..............
.A....................
.2....................
......................

[chip] 
[type] UC6
[x] 4
[y] 2
[code] 
  slx x0
  mov x1 acc
  mov x1 dat
  mov acc x3
  mov dat x3
  mov acc x3
  mov dat x3

[chip] 
[type] UC6
[x] 8
[y] 5
[code] 
  slx x2
  mov x2 x1
  mov x0 dat
  mov x2 x1
  mov x0 acc
  mov x2 x1
  mov dat 

[chip] 
[type] UC4X
[x] 2
[y] 6
[code] 
  slx x0
  mov 0 x3
j:  mov x0 acc
  mov acc x2
  teq acc 0
- jmp j
  mov -999 x1

[chip] 
[type] RAM
[x] 5
[y] 6

SIO

免责声明:数组以0结尾。否则,在深圳I / O中使用数组是一件很麻烦的事情。

我实际上为这款游戏设定了蒸汽强度。你可以在这里

编辑:Aaand我刚刚意识到我说的数组是有序的。哎呀


欢迎来到网站,这真的很酷!您认为您是否可以删除文件中的某些空白,但深圳IO仍接受该文件?我不知道您花了多少钱,但是您应该尝试看看格式是否灵活。
小麦巫师

我还没有玩过!另一方面,我正在更改包含谜题名称和解决方案名称的谜题的标题,因此我不愿意打扰。
junkmail

1

Swift,111个 65字节(0索引)

Swift已经成为最差的代码高尔夫语言之一而臭名昭著,但这是一个使用三元表达式的函数:

func t(l:[Int],m:Int,n:Int){var r=l;r[m]=l[n];r[n]=l[m];print(r)}

看看这个! - 用法: t(l:[1,2,3],m:0,n:1)


Using a default param for r would save you bytes and you can also just mutate the passed array (AFAIK swift array are pass by value)
Downgoat

Default parameter in Swift? How can I do that?
Mr. Xcoder

And parameters are constants in Swift @Downgoat
Mr. Xcoder

1

k (kona), 13 bytes

{x[y]:x@|y;x}

Pretty basic, but it works. Ex:

k){x[y]:x@|y;x}[1 2 3 4; 0 1]
2 1 3 4

1

Perl 5, 32 bytes

-3 bytes thanks to @Dom Hastings!

30 bytes of code + -pa flags.

@F[pop@p,@p]=@F[@p=<>];$_="@F"

Try it online!

Quite straight forward, using array slices.


Hey hey, tinkered with this a little and managed to save 3 bytes! @F[pop@p,@p]=@F[@p=<>];$_="@F".
Dom Hastings

@DomHastings Hmm, nice, as always! Thanks :)
Dada

1

Mathematica, 32 bytes

(a=#;a[[{##2}]]=a[[{#3,#2}]];a)&

3
a[[{##2}]]==a[[{#3,#2}]] should be a[[{##2}]]=a[[{#3,#2}]] (using Set, not Equals)
JungHwan Min

1

C, 42 bytes

Modify the array in place with a temp value.

f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;}

C, 60 58 bytes

A little more interesting, not using any temp value...

f(a,m,n)int*a;{a[m]+=a[n];a[n]-=a[m];a[n]*=-1;a[m]-=a[n];}

C, 49 bytes

Using XOR

f(a,m,n)int*a;{a[m]^=a[n];a[n]^=a[m];a[m]^=a[n];}

Heh, I was just about to post f(x,i,j,t)int*x;{t=x[i];x[i]=x[j];x[j]=t;}.
Dennis

@Dennis you saved me two bytes on the other solution, thanks!
cleblanc

Wouldn't the second solution be shorter (and safer) with ^?
Dennis

-1 for the XOR version using a define instead of a function #define X(x,y,z)x[y]^=x[z],x[z]^=x[y],x[y]^=x[z]
Giacomo Garabello

f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;} is broken: SIGSEGV.
Bodo Thiesen

1

Pyth, 17 8 bytes

Saved 9 bytes thanks to Leaky Num.

@LQ.rUQE

Test it online!

This is 0-indexed, and the indices are provided as a tuple: (n, m).

Explanations

@LQ.rUQE

     UQ     # Generate [0, 1, 2, ..., len(input)]
       E    # Get the indices as the tuple (1, 2)
   .r       # Translate each element of UQ to its cyclic successor in E
            # Now the indices are permuted (e.g. [0, 2, 1, ..., len(input)]
@LQ         # For each index, get it's value. Implicit print

8 bytes: @LQ.rUQE
Leaky Nun

@LeakyNun It's so different I think you can post it for yourself!
Jim

I'm the OP; I don't post on my own challenge.
Leaky Nun

1

Mathematica, 20 bytes

#~Permute~Cycles@#2&

Pure function taking two arguments in the following 1-indexed (and possibly abusive) format: the second test case [5,8,9]; 0 2; [9,8,5] would be called as

#~Permute~Cycles@#2& [ {5,8,9} , {{1,3}} ]

(spaces are extraneous and just for visible parsing). Permute is the builtin function that applies a permutation to a list, and Cycles[{{a,b}}] represents the permutation that exchanges the ath and bth elements of a list and ignores the rest.


What do the ~ do?
Cyoce

~ is Mathematica's infix notation for a binary function: x~f~y means the same thing as f[x,y].
Greg Martin

1

x86 Machine Code, 10 bytes

8B 04 8B 87 04 93 89 04 8B C3

This is a function written in 32-bit x86 machine code that swaps the values at the specified indices in a given array. The array is modified in-place, and the function does not return a value.

A custom calling convention is used, requiring the function's parameters to be passed in registers:

  • The address of the array (pointer to its first element) is passed in the EBX register.
  • The zero-based index of element A is passed in the ECX register.
    (Assumed to be a valid index.)
  • The zero-based index of element B is passed in the EDX register.
    (Assumed to be a valid index.)

This keeps the size down and complies with all formal requirements, but does mean that the function cannot be easily called from other languages like C. You'd need to call it from another assembly-language program. (You could rewrite it to use any input registers, though, without affecting the byte count; there's nothing magical about the ones I chose.)

Ungolfed:

8B 04 8B     mov  eax, DWORD PTR [ebx+ecx*4]   ; get value of element A
87 04 93     xchg eax, DWORD PTR [ebx+edx*4]   ; swap element A and element B
89 04 8B     mov  DWORD PTR [ebx+ecx*4], eax   ; store new value for element A
C3           ret                               ; return, with array modified in-place


1

Java 8 + InverseY, 27 bytes

java.util.Collections::swap

Just calls the swap function... this is a method reference of the type Consumer3<List, Integer, Integer>.

Try it online! (header and footer for boilerplate & copy of Consumer3 interface)


You don't need to add " + InverseY". It's valid in vanilla Java 8.
Olivier Grégoire

1

JavaScript (ES2015), 66 57 49 bytes

A different (alas, longer) approach than previous JavaScript answers

(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h]))

Source

const swap = (arr, a, b, splice) => {
  splice(a, 1, ...splice(arr[b], 1, arr[a]))
}

1
(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h])) 49 bytes
Patrick Roberts

Forgot about them default args. Thanks!
sshow

0

awk, 31 bytes

{c=$a;$a=$b;$b=c;a=$1;b=$2}NR>1

Try it online!

Takes input in the format

1 2
1 2 3 4

and outputs as

2 1 3 4

(1-indexed).

Explanation

The entire program is a missing pattern with an action followed by a pattern with a missing action.

Since a missing pattern runs on each line, the code inside the braces runs for both input lines. The c=$a;$a=$b;$b=c; part swaps the two values at indices a and b (through the temporary variable c). This only has an effect on the second line, since on the first line a and b are not yet defined. The a=$1;b=$2 part defines a to be the first field and b to be the second field, which sets the appropriate values for the first part to run on the second line.

Since a missing action is equivalent to {print}, the pattern prints every line it matches. This pattern in particular is NR>1: that is, print whenever the line number is greater than 1, which happens to be line 2. This runs after the swapping of values has taken place, thus completing the task.


0

q/kdb+, 17 bytes

Solution:

{@[x;(|)y;:;x y]}

Example:

q){@[x;(|)y;:;x y]}[1 2 3 4;0 1]
2 1 3 4

Explanation:

A q version of the k answer by Simon. Apply the assign : function to x at indices reverse-y with value of x indexed at y. Broken down you can see more clearly:

q)x:1 2 3 4
q)y:0 1
q)x y
1 2
q)(|)y
1 0
q)x(|)y
2 1
q)@[x;(|)y;:;x y]
2 1 3 4
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.