4
\$\begingroup\$

Exchange the Stacks!

Write a program that can exchange any character from two stacks. In this challenge, a stack is a tower of characters. An example stack is below:

1
a
4
d
*
c
3

There are two stacks involved in the challenge and both are inputted when the program runs. The program will also be given an argument of which position in Stack 1 to exchange with stack 2. So if the stacks look like this:

STACK 1

a
$
5
D
0
)
_

STACK 2

^
p
0
-
@
L
m

and the program is told to exchange position 2, the resulting stacks will look like this:

STACK 1

a
p
5
D
0
)
_

STACK 2

^
$
0
-
@
L
m

and the program should output them. The program should run with any stack size, not just 7, and should work with all standard characters (characters that are easily types at the keyboard, without using fancy stuff like Alt codes). Space is not required to work. Your program should accept three inputs: The contents of stack 1, the contents of stack 2 and the character to swap. Inside the program, I don't mind what form the stacks take, but when they are outputted, it must be in the form of each character separated by a newline. Input can be in any form.

Scoring

This is and so the least bytes wins!

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

var QUESTION_ID=57831;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>

\$\endgroup\$
  • \$\begingroup\$ Can the stacks be space-separated instead of newline-separated? That would be a lot easier for the input. \$\endgroup\$ – ProgramFOX Sep 13 '15 at 8:36
  • \$\begingroup\$ @ProgramFOX Hmm... Do I want it easy? Guess it doesn't make it too easy, so yeah, OK. \$\endgroup\$ – user42003 Sep 13 '15 at 8:38
  • \$\begingroup\$ @ProgramFOX Just checking: You are talking about the output, yeah? \$\endgroup\$ – user42003 Sep 13 '15 at 8:39
  • \$\begingroup\$ No, I'm talking about the input. You have to get those two stacks inputted, but if you press enter for each stack item, how do you know when you have to start receiving input for a new stack? Or that you're ready inputting stacks? \$\endgroup\$ – ProgramFOX Sep 13 '15 at 8:45
  • \$\begingroup\$ when they are outputted, it must be in the form of each character separated by a space in your examples, they are separated by line breaks \$\endgroup\$ – Fatalize Sep 13 '15 at 8:51
5
\$\begingroup\$

Python 3, 107 bytes

This account's first golf ;)

x,y,p=input(),input(),int(input())-1
print('\n'.join(x[:p]+y[p]+x[p+1:])+'\n'+'\n'.join(y[:p]+x[p]+y[p+1:]))

Takes input as three lines, the first being the first stack, the second line, the second stack and the third, the position.

Outputs the stack as separated by newlines.

\$\endgroup\$
  • 9
    \$\begingroup\$ Welcome to PPC... G........ wait a sec \$\endgroup\$ – undergroundmonorail Sep 13 '15 at 16:57
  • 1
    \$\begingroup\$ @undergroundmonorail I don't know what you're talking about ;) \$\endgroup\$ – Alpha Decay Sep 13 '15 at 18:00
  • 7
    \$\begingroup\$ @undergroundmonorail Yeah, lay off the poor guy :D \$\endgroup\$ – Beta Decay Sep 13 '15 at 18:01
  • 1
    \$\begingroup\$ Be nice to each other, or I'll have to summon the mighty Gamma Decay! \$\endgroup\$ – Luis Mendo Sep 13 '15 at 23:17
2
\$\begingroup\$

CJam, 16 17 bytes

Didn't notice the position was 1-based. Fixed now, at the cost of 1 byte.

ll+_,2/li(_@+e\N*

Takes the input on three lines:

Stack 1
Stack 2
Position (1-based)

Also supports spaces in the stacks. Outputs the swapped stacks, one character per line.

Try it online.

Explanation

ll+               e# Concatenate first two lines
   _,2/           e# Push half length (size of one stack)
       li(        e# Read third line as integer, subtract 1
          _@+     e# Sum a copy of the position with the stack size
             e\   e# Swap (position) <-> (position + stack size)
               N* e# Join with newline
\$\endgroup\$
1
\$\begingroup\$

AutoIt, 135 132 129

$l=$CmdLine
$d=StringLen($l[1])
$b=$l[2]
$c=$d/2+$b
For $n=1 To $d
ConsoleWrite(StringMid($l[1],$n=$b?$c:$n=$c?$b:$n,1)&@LF)
Next

Run like this:

compiled.exe abccba 1

where abccba are both stacks concatenated and 1 is the switch position (1-based). Supports spaces and all unicode characters. Output:

c
b
c
a
b
a
\$\endgroup\$
1
\$\begingroup\$

C#, 238 222 213 bytes

namespace System.Linq{class A{static void Main(string[]a){int n=int.Parse(a[2])-1;Console.Write(string.Join("\n",a[0].Select((x,i)=>i==n?a[1][n]:x))+"\n\n"+string.Join("\n",a[1].Select((x,i)=>i==n?a[0][n]:x)));}}}

To execute:

compiled.exe <stack 1> <stack 2> <index to exchange>

The stacks have to be inputted without separator between the stack items, e.g. compiled.exe abcdef 123456 2.

Thanks to Andrea Biondo for saving 25 bytes!

Ungolfed code:

using System;
using System.Linq;

namespace ExchangingStacks
{
    class Program
    {
        static void Main(string[] args)
        {
            string stack1 = args[0];
            string stack2 = args[1];
            int exchangeIndex = int.Parse(args[2]) - 1;
            var newStack1 = stack1.Select((x, index) => index == exchangeIndex ? stack2[exchangeIndex] : x);
            var newStack2 = stack2.Select((x, index) => index == exchangeIndex ? stack1[exchangeIndex] : x);
            Console.Write(string.Join("\n", newStack1) + "\n\n" + string.Join("\n", newStack2));
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ I don't really know C#, but you can save 16 bytes by removing b and c and placing the Select calls as arguments in the string.Join calls. \$\endgroup\$ – Andrea Biondo Sep 13 '15 at 9:45
  • \$\begingroup\$ @AndreaBiondo Nice, thanks! \$\endgroup\$ – ProgramFOX Sep 13 '15 at 9:54
  • \$\begingroup\$ Also replace all s with a[0] and all t with a[1] and remove s and t, another 9 chars gone :) \$\endgroup\$ – Andrea Biondo Sep 13 '15 at 11:15
  • \$\begingroup\$ @AndreaBiondo Cool, thanks again! \$\endgroup\$ – ProgramFOX Sep 14 '15 at 16:03
1
\$\begingroup\$

PowerShell, 81 Bytes

param([char[]]$a,[char[]]$b,$n);$n--;$t=$b[$n];$b[$n]=$a[$n];$a[$n]=$t;$a;"`n";$b

Holy Dollar Signs, Batman! 16 of the 81 characters (~20%) are $.

The input is expected to be literal-string delimited and space-separated, thanks to the very liberal input requirements. If one of the input stacks includes the ' character, it will need to be escaped with a backtick. Example of the input from the question:

.\exchange-the-stacks.ps1 'a$5D0)_' '^p0-@Lm' 2

Pretty simple char-array manipulation. PowerShell, by default, when "executing" an array, will print each item on its own line, so simply $a will output each element newline-separated, hence why this is so competitive with other non-golfing languages, as we don't need to specially format the output.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy