주어진 두 지수를 교환


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
놀랍게도 이것은 속임수가 아니지만 놀랍습니다. 그러나이 도전은 실제로 많은 골프 언어에있어 진정한 도전이기 때문에 실제로 창의적입니다.
아웃 골퍼 에릭

@LeakyNun 나는 어떻게하지 그것에 대해 너무 걱정, 과거에 ... 그런 downvotes (심지어 삭제 표)를 가지고있다
에릭 Outgolfer

mn배열로한다?
Okx

답변:



10

인화점 스크립팅 언어, 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

자바 스크립트 ES6, 36 32 바이트

봐봐, 임시 변수는 없어!

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

시도 해봐

&에 대해서는 쉼표로 구분 된 요소 목록 a과 2 개의 정수를 입력하십시오 .mn

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

@ 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.

tfw 래퍼는 프로그램만큼 거의 ...
Leaky Nun

나는 존재를 몰랐다y
Leaky Nun

나는 알고 있었지만 y여기서는 사용하지 않았다. 그것은 꽤 영리한 대답입니다.

이것은 나를 생각하게했다 ... Jelly유효한 젤리 코드인가?
M.Herzkamp

@ M.Herzkamp입니다. 그래도 그 유용성이 의심 스럽다.
데니스


4

MATL , 7 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]

4

C # (. NET 코어) , 48 43 31 바이트

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

온라인으로 사용해보십시오!

임시 변수를 사용하지 않고 원래 배열의 숫자를 바꿉니다. 그럼에도 불구하고 나는이 답변이 Neil의 아이디어 였기 때문에 신용을 얻을 수 없습니다 .


@LeakyNun 값이 0 인 a [m]을 남기므로 작동하지 않는 것 같습니다 . 직접 사용해보십시오!
Charlie

(a,m,n)=>a[m]+=a[n]-(a[n]=a[m])그래도 작동하는 것 같습니다.
Neil

(이 답변은 모두 ES6 JavaScript에서도 유효합니다.)
Neil


3

자바 스크립트 ES6, 36 34 바이트

(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)
  • 함수가 배열을 변경하고 있기 때문에 -2 바이트. 배열을 반환 할 필요가 없습니다. @Neil에게 감사합니다

데모


1
이 명령어는 배열을 수정하므로 배열을 반환하지 않아도되므로 몇 바이트가 절약됩니다.
Neil


2

자바 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에서 세 가지 인수로 람다를 어떻게 수행합니까?
Leaky Nun

1
Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes.
Neil

1
@LeakyNun I'm not Okx, but here is a Try it now example with Okx's current answer and custom interface.
Kevin Cruijssen

1
And based on Carlos Alejo's amazing C# answer (with @Neil's help), you can make it even shorter by getting rid of the temporary variable: (a,b,c)->a[b]+=a[c]-(a[c]=a[b]) (31 bytes)
Kevin Cruijssen

1
cough cough Collections::swap is 17 bytes... at least assuming this holds for this challenge...
Socratic Phoenix


2

Octave, 28 bytes

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

Try it online!

Quite satisfied with this one actually :)

Takes input on the form: f([1,2,3,4],[1,2]), 1-indexed.

Explanation:

@(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

Jellyfish, 7 bytes

p
ZRi
i

Takes a list and a pair of indices. Try it online!

Explanation

Jellyfish happens to have a "modify items at indices" function, Z, which does exactly what we need. The two is grab the inputs from STDIN. Z takes as arguments the second input, the reversal function R, and the list. Then Z performs the modification, and p prints the result.


2

R, 38 bytes

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

Feels rather long, but I can't get it much shorter. Sadly it requires the explicit returning through x, requiring {} around the function body. pryr::f() doesn't recognise the need for x as function argument so doesn't work :/.


I think function(x,i)replace(x,i,rev(i)) would work, even with pryr syntax.
Giuseppe

@Giuseppe Ah, I was looking for a convenient function to do the swap, but was searching with the wrong terms. Feel free to post that as an own answer.
JAD

@Giuseppe I think you need to do replace(x,i,x[rev(i)]), else you'll place the indices instead of their values.
JAD

2

Shenzhen I/O, 735 Bytes

23¥, 810 Power, 48 Lines of Code

[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

DISCLAIMER: Arrays are 0-terminated in this. Arrays are a pain in the ass to work with in Shenzhen I/O otherwise.

I actually made a steam level for this game. You can play it here.

EDIT: Aaand I just realized I said that the array in was ordered. Heck.


Welcome to the site This is really cool! do you think that you might be able to remove some of the whitespace in the file and still have Shenzhen IO accept the file? I don't know how much you have fiddled with it, but you should try and see how flexible the format is.
Wheat Wizard

I haven't played around with it! On the other hand, I am axing the header for the puzzle which contains the puzzle name and solution name, so I dunno if I should bother.
junkmail

1

Swift, 111 65 bytes (0-indexed)

Swift is already notorious for being one of the worst code-golf languages, but here is a function that makes use of ternary expressions:

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

Check it out! - Usage: 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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.