Robot on a ladder

30

1

Background

I have a ladder leaning on a wall, and a remote-controlled robot that can climb it. I can send three different commands to the robot:

  • UP: the robot takes one step upwards. If it was on the highest step, it trips over, falls down and explodes.
  • DOWN: the robot takes one step downwards. If it was on the lowest step, nothing happens.
  • RESET: the robot returns to the lowest step.

I can also send a series of commands, and the robot will execute them one by one. Your task is to predict its movements.

Input

Your inputs are a positive integer N, representing the number of steps in the ladder, and a non-empty string C over UDR, representing the commands I have sent to the robot. You can assume that N < 1000. The robot is initialized on the lowest step of the ladder.

Output

It is guaranteed that at some point, the robot will climb over the highest step and explode. Your output is the number of commands it executes before this happens.

Example

Consider the inputs N = 4 and C = "UDDUURUUUUUUUDDDD" The robot, denoted by @, moves along the 4-step ladder as follows:

|-|   |-|   |-|   |-|   |-|   |-|   |-|   |-|   |-|   |@|   |-||
|-|   |-|   |-|   |-|   |-|   |@|   |-|   |-|   |@|   |-|   |-||
|-|   |@|   |-|   |-|   |@|   |-|   |-|   |@|   |-|   |-|   |-|v
|@| U |-| D |@| D |@| U |-| U |-| R |@| U |-| U |-| U |-| U |-|# Boom!

The remaining commands are not executed, since the robot has exploded. The explosion took place after 10 commands, so the correct output is 10.

Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

Test cases

  1 U -> 1
  1 DDRUDUU -> 4
  4 UDDUUUUURUUUUDDDD -> 7
  4 UDDUURUUUUUUUDDDD -> 10
  6 UUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR -> 20
 10 UUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU -> 34
  6 UUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU -> 8
  6 UUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU -> 32
 20 UUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU -> 56
354 UUDDUUDU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DUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU -> 872

Zgarb

Posted 2016-03-01T20:32:01.117

Reputation: 39 083

1Related – Peter Taylor – 2016-03-01T20:50:47.503

8I'm disappointed the task isn't to generate that ASCII art. – user253751 – 2016-03-02T02:34:34.400

6

@immibis You know what to do...

– Martin Ender – 2016-03-02T12:31:36.473

Instead of a string, can we take a list of character codes? – Cyoce – 2016-03-03T03:04:57.940

@Cyoce Only if your language has no other means to represent a string. – Zgarb – 2016-03-03T03:57:05.870

@Zgarb what about a list of commands (characters)? – Cyoce – 2016-03-03T04:37:36.977

@Cyoce Same answer, only if that's how your language represents strings. – Zgarb – 2016-03-03T04:40:41.417

Answers

10

CJam, 26 25 22 bytes

0l{i"()~ "=~0e>_}%ri#)

Input format is the instructions on the first line and the ladder height on the second.

Test it here.

Explanation

0         e# Push a 0 - the initial position of the robot.
l         e# Read the instructions.
{         e# Map this block over the instruction...
  i       e#   Convert to character code. D -> 68, U -> 85, R -> 82.
  "()~ "= e#   We use these as cyclic indices into this array. Note that the values
          e#   modulo 4 are 0, 1 and 2, respectively. So U -> ) (increment),
          e#   D -> ( (decrement), R -> ~ (bitwise NOT, i.e negated and decrement).
  ~       e#   Evaluate the character as code.
  0e>     e#   Clamp to non-negative numbers. So D can't go below 0, and since R is
          e#   guaranteed to yield something negative, this resets it to zero.
  _       e#   Duplicate, so we keep one copy of the current position on the stack.
}%        e# Since this was a map, the result will be wrapped in an array.
ri        e# Read the ladder height and convert it to an integer.
#         e# Find its first occurrence in the list of positions.
)         e# The result is off by one, so we increment it.

Martin Ender

Posted 2016-03-01T20:32:01.117

Reputation: 184 808

Good idea to process all commands even after the explosion. I'll borrow that to save a few bytes – Luis Mendo – 2016-03-01T22:36:42.543

7

C, 83 71 + 4 = 75 bytes

Thanks @Josh for showing me the K&S style, which allowed 8 bytes off !!

f(i,s,z,a)char*s;{z-=*s<82?z>0:*s>82?-1:z;return z-i?f(i,s+1,z,a+1):a;}

Explaining:

f(i,s,z,a)char*s;{ // function needs one integer and one "string"
  z-=              // z is the bot's height
    *s<82?         // if 'Down'
      z>0          // then subtract 1 when z>0 or nothing otherwise
    :*s>82?        // else if 'Up'
      -1           // increase height z-=-1
    :z;            // else reset z=z-z
  return z-i?      // if z is not the max height
    f(i,s+1,z,a+1) // try next step
  :a;              // else print how many calls/steps were made
}                  // end of function

Example call:

f(1,"U",0,1);    // I've added 4 bytes in the score because of ",0,1"

Live test on ideone

removed

Posted 2016-03-01T20:32:01.117

Reputation: 2 785

1Nice answer, but it might be worth noting that the function can effectively only be used once since globals z and a are not reset. – Josh – 2016-03-02T22:06:59.710

@Josh. I've updated. :) – removed – 2016-03-03T13:00:19.323

1

Awesome! You can also save a couple characters by playing around with the type declarations in your function: http://codegolf.stackexchange.com/a/40266/13877

– Josh – 2016-03-03T13:43:52.703

@Josh. Wow this is awesome! thanks – removed – 2016-03-03T14:19:19.613

6

JavaScript (ES6), 54 53 bytes

n=>c=>(f=p=>n-p?f({D:p&&p-1,U:p+1}[c[i++]]|0):i)(i=0)

Explanation

Uses a recursive function internally.

var solution =

n=>c=>(
  f=p=>             // f = recursive function, p = position of robot on ladder
    n-p?            // if p != n
      f({           // execute the next command
          D:p&&p-1, // D -> p = max of p - 1 and 0
          U:p+1     // U -> p = p + 1
        }[c[i++]]   // get current command then increment i (current command index)
        |0          // R -> p = 0
      )
    :i              // else return the current command index
)(i=0)              // initialise p and i to 0 for the first recurse
N = <input type="number" id="N" value="354" /><br />
C = <input type="text" id="C" value="UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDU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ution(+N.value)(C.value)">Go</button>
<pre id="result"></pre>

user81655

Posted 2016-03-01T20:32:01.117

Reputation: 10 181

4

JavaScript (SpiderMonkey 30+), 65 64 bytes

(n,s,i=0)=>[for(c of s)if(i<n)c<'E'?i&&i--:c>'T'?i++:i=0].length

How it works

We first set the variable i to 0. This will keep track of how many steps the robot has climbed up. Then for each char c in the input string, we run the following logic:

  1. If i is larger than or equal to n, don't do anything.
  2. If c is "D":
    • If i is 0, leave it as is.
    • Otherwise, decrement it by 1.
  3. If c is "U", increment i by 1.
  4. Otherwise, set i to 0.

By cutting off if i>=n, we avoid adding any more items to the array after the robot has reached the top. Thus, we can simply return the length of the resulting array.

ETHproductions

Posted 2016-03-01T20:32:01.117

Reputation: 47 880

4

Perl, 47 + 2 = 49 bytes

$z-=-/U/||$z&&/D/;$z*=!/R/;$^I<=$z&&last}{$_=$.

Requires the -p flag, -i$N for latter height and a newline separated list of moves:

$ perl -pi10 ladderbot.pl <<<< $'U\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU'
34

How it works:

                                                # '-p' wraps the code in (simplified):
                                                # while($_=<>) {...print $_}
$z-=-/U/||$z&&/D/;                              # Subtract -1 if UP. subtract 1 if DOWN
                  $z*=!/R/;                     # If R then times by zero
                           $^I<=$z&&last        # Break while loop if N is reached
                                        }{      # Eskimo operator:
                                                # while($_=<>){...}{print$_}
                                          $_=$. # `$.` contains number of lines read from input.

Deparsed:

LINE: while (defined($_ = <ARGV>)) {
    $z -= -/U/ || $z && /D/;
    $z *= !/R/;
    last if $^I <= $z;
}
{
    $_ = $.;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

andlrc

Posted 2016-03-01T20:32:01.117

Reputation: 1 613

3

Haskell, 65 bytes

x%'U'=x+1
x%'D'=max(x-1)0
x%_=0
f n=length.fst.span(<n).scanl(%)0

Usage example: f 4 "UDDUURUUUUUUUDDDD" -> 10.

% adjusts the current position on the ladder, scanl makes a list of all positions, fst.span(<n) takes the part before the explosion and length counts the steps.

nimi

Posted 2016-03-01T20:32:01.117

Reputation: 34 639

Nice job with the combination of named arguments and composition/currying – Cyoce – 2016-03-03T02:23:43.693

3

JavaScript (ES6), 65 bytes

(n,s)=>[...s].map(_=>i=_<'E'?i&&i-1:_>'T'?i+1:0,i=0).indexOf(n)+1

Charlie Wynn

Posted 2016-03-01T20:32:01.117

Reputation: 696

1

Let us continue this discussion in chat.

– ETHproductions – 2016-03-01T21:28:46.093

I think 0,i=0 can be changed to i=0 – Cyoce – 2016-03-03T00:29:13.317

@Cyoce hmm, fails for me in a new tab (works on this page b/c i is already defined) – Charlie Wynn – 2016-03-03T14:04:49.290

@CharlieWynn sorry, got my precedence mixed up – Cyoce – 2016-03-03T18:18:39.697

3

PowerShell, 86 79 bytes

param($a,[char[]]$b)$b|%{$d++;if(($c-=((1,0)[!$c],-1,$c)[$_%4])-ge$a){$d;exit}}

A slight retooling of my When does Santa enter the basement? answer.

Takes input $a and $b, explicitly casting $b as char-array. We then loop with |%{...} over all of $b. Each iteration we increment our counter $d.

Then, an if statement to check whether we've hit the top with -ge$a. If so, we output $d and exit. The if statement is constructed from a pseudo-ternary created by assigning $c minus-equal to the result of several indexes into an array.

We have a trick that the ASCII values of D, R, and U correspond to 0, 2, and 1 when taken modulo-4, so $_%4 serves as our first index. If it's R, that sets $c equal to $c-$c, doing the reset. If U, that means we need to go up, so the $c-(-1) result. Otherwise it's a D, so we need to check if we're already at the bottom (that's the !$c - in PowerShell, "not-zero" is "true" or 1) and set $c equal to $c-0 or $c-1 respectively.

Edit - Saved 7 bytes by using minus-equal assignment rather than direct assignment

AdmBorkBork

Posted 2016-03-01T20:32:01.117

Reputation: 41 581

3

Perl 5, 61 bytes

Includes two bytes for -F -i. (-M5.01 is free.)

Input of the integer (e.g. 10) is as perl -M5.01 -F -i10 robot.pl; input of the ladder commands is as STDIN.

for(@F){($i+=/U/)-=/R/?$i:$i&&/D/;$j++;last if$^I<=$i}say$j

msh210

Posted 2016-03-01T20:32:01.117

Reputation: 3 094

using perl 5.12.5, i also had to explicitly enable autosplit mode with -anF before it would print anything for me. but it seems to get implicitly enabled with only -F in 5.20.3. can you verify this? – ardnew – 2016-03-02T02:23:27.997

@ardnew, just -F sufficed for me (5.20 or 5.22 or so). Iirc the current perldoc perlrun says it implies -a and -a implies -n. – msh210 – 2016-03-02T03:55:51.680

How much does we count -i for? I can see you count it as 1 but I would guess it should actually be counted as 3? :-) – andlrc – 2016-03-03T09:48:14.940

@dev-null, why three? I think the convention on PPCG.SE is to count the letters in a flag but not the hyphen-minus characters, but please correct me if I'm wrong. (It looks like you're using the same counting convention for yoru own answer to this question, too. (Incidentally, nice answer.)) – msh210 – 2016-03-03T15:09:56.647

@msh210 I was just counting the difference when using -i and without perl -i10 -pe';' vs perl -pe';' 3 characters more and then the input number - which I guess we shouldn't count. But I might be wrong just though about it this morning :-) – andlrc – 2016-03-03T15:57:21.367

@dev-null, but why not count p? – msh210 – 2016-03-03T16:02:27.207

@msh210 p would only be counted as 1 because it can be stacked together with e. – andlrc – 2016-03-03T16:15:44.973

3

MATL, 37 34 bytes

Oj"t@4\1=?Q}6M?x0}qt0>*]]]N$h=f1)q

Try it online!

Explanation

Position is 0-based. Each new position is pushed onto the stack keeping the older positions. So the stack size represents the number of movements up to now, plus 1.

A loop is used to process each command. The loop is exited when position reaches ladder height processes all commands, even after the explosion (idea taken from Martin's answer). The final result is given by the index of the first position that equals the ladder height.

O             % push a 0: initial position (0-based)
j             % take first input (commands) as a string
"             % for each command
  t           %   duplicate current position
  @           %   push command
  4\          %   modulo 4. This gives 1, 2, 0 for 'U','R', 'D'
  1=?         %   if result equals 1 (command 'U')
    Q         %     increase position by 1
  }           %   else
    6M?       %     if result was nonzero (command 'R')
      x0      %       delete current position and push 0
    }         %     else (command 'D')
      q       %       decrement by 1
      t0>*    %       turn negative values into 0
    ]         %     end if
  ]           %   end if
]             % end for each
N$h           % pack all numbers in the stack into an array
=             % implicitly read second input: ladder height
f1)q          % find first position equal to that, and subtract 1.
              % Implicitly display

Luis Mendo

Posted 2016-03-01T20:32:01.117

Reputation: 87 464

3

Python 2, 63 62 bytes

f=lambda n,s,h=0:h^n and-~f(n,s[1:],-[2%~h,~h,0][ord(s[0])%4])

For example, f(4, 'UDDUURUUUUUUUDDDD') is 10.

xnor found an even shorter expression: 2%~h is really cool :)

Lynn

Posted 2016-03-01T20:32:01.117

Reputation: 55 648

Nice find with the %4. If I'm not mistaken, you can save a character by doing -[2%~h,~h,0][ord(s[0])%4]. – xnor – 2016-03-02T05:15:11.423

3

Vitsy, 44 bytes

There probably could be some reductions - I'll figure out some more things if I can.

0vVWl:X[4M1+mDvV-);]lvXv?v-N
vD([1-]
v1+
vX0

Explanation (in progress):

0vVWl:X[4M1+mDvV-);]lvXv?v-N
0v             Save 0 as our temp var to edit.
  V            Save the input as a global var.
   W           Grab a line of STDIN.
    l          Push the length of the stack.
     :         Clone the stack. This is for later use.
      X        Remove the top item of the stack (we don't need the length right now.
[            ] Do the stuff in the brackets infinitely.
 4M            Modulo 4.
   1+          Add one.
     m         Go to the line index as specified by the top item of the stack.
      Dv       Duplicate the top item, save it in the temp var.
        V-);   If the top value is equal to the input number, exit the loop.
l              Push the length of the stack.
 vXv           Dump the temp var, then save the top item.
    ?          Rotate back to the original stack.
     v-        Subtract the top item (the original length) by the temp var (new length)
       N       Output the top item of the stack of the number.

vD([1-]
v              Push the temp variable to the stack.
 D([  ]        If this value is not zero...
    1-         Subtract one from it.

v1+            Push the temp variable to the stack, then add one to it.

vX0            Dump the temp var and replace it with zero.

Try It Online! (big test case)

Addison Crump

Posted 2016-03-01T20:32:01.117

Reputation: 10 763

2

Python 3, 90

Saved 6 bytes thanks to DSM.

Pretty simple right now.

def f(c,n):
 f=t=0
 for x in c:
  f+=1|-(x<'E');f*=(x!='R')&(f>=0);t+=1
  if f>=n:return t

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UUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU', 354) == 872

Morgan Thrapp

Posted 2016-03-01T20:32:01.117

Reputation: 3 574

2

JavaScript, 131 106 Bytes-

I know this won't win a Code Golf competition, but this was a fun and stupid solution to implement:

l=>s=>Function('i=c=0;'+s.replace(/./g,x=>`c++;i${{R:"=0",U:`++;if(i>=${l})re‌​turn c`,D:"--"}[x]};`))()

I kinda went the opposite of a "functional" route by making a dynamically-generated imperative solution, any instance of an instruction is replaced with an increment or decrement, and a counter increment.

Thanks to Cycoce for saving me 29 bytes!

DLeh

Posted 2016-03-01T20:32:01.117

Reputation: 1 111

Here, I golfed off 29 bytes: l=>s=>Function('i=c=0;'+s.replace(/./g,x=>\c++;i${{R:"=0",U:`++;if(i>=${l})return c`,D:"--"}[x]};`))()` – Cyoce – 2016-03-03T03:55:37.690

2

Python, 121 bytes

def f(a,n):
 i=c=0
 while i<n:i={'U':lambda x:x+1,'D':lambda x:0 if x==0 else x-1,'R':lambda x:0}[a[c]](i);c+=1
 return c

Alex Burge

Posted 2016-03-01T20:32:01.117

Reputation: 31

1Welcome to PPCG! Here we require by default that answers are either full programs that take input from STDIN and print to STDOUT, or functions that take inputs as arguments and return the output value. Your solution hard-codes the inputs, which is not allowed. – Zgarb – 2016-03-01T23:39:38.847

Corrected by forming into function, I was using interpreter when I wrote it. – Alex Burge – 2016-03-01T23:48:16.567

Thank you! You should also add a header of the form ## Python, <N> bytes to show others your score. – Zgarb – 2016-03-01T23:58:25.253

I don't think there can be an unnamed function. – user48538 – 2016-03-02T08:08:06.063

You can save bytes by replacing 0 if x==0 else x-1 with x and x-1 – Cyoce – 2016-03-03T00:22:13.863

2

PHP, 88 bytes

This generates some (3+2n where n is the number of commands run) notices but that doesn't matter for golfing, right?

<?php for(;$x++<$argv[1];)switch($argv[2][$i++]){case R;$x=2;case D;--$x?--$x:0;}echo$i;

ungolfed:

<?php                    # actually 1 byte shorter not as a function
for(;$x++<$argv[1];)     # not initialising the $x causes a notice but still works
                         # post increment $x by 1 regardless of the command (saves us writing a U case)
  switch($argv[2][$i++]) # get next command, increment number of commands
    {case R;             # R gets treated as a constant with value 'R'. and a notice
      $x=2;              # falling through to D which will double decrement so set to 2
    case D;              # same trick as R
      --$x?--$x:0;}      # decrement once then again if >0
echo$i;                  # output

user51805

Posted 2016-03-01T20:32:01.117

Reputation: 31

Notices are fine, as long as the code can still be run. – Zgarb – 2016-03-02T19:44:36.820

1

PHP, 129 bytes

function r($h,$s){$i=0;$c=1;while($x=$s[$i++]){if($x=='U'){$c++;}elseif($x=='D'){--$c<1?$c=1:0;}else{$c=1;}if($c>$h){return$i;}}}

Not winning, but fun to create. PHP seems to dislike empty parts in the ternary operator (it throws a Syntax Error), so I had to put a 0 there.

Ungolfed version:

function r($h,$s) {          // $h - height of ladder; $s - instructions
  $i = 0;                    // Instruction index
  $c = 1;                    // Position on ladder
  while ($x = $s[$i++]){     // Set $x to current instruction and increment index
    if ($x == 'U'){          // If instruction is U...
      $c++;                  // Increment ladder position
    } elseif ($x == 'D') {   // If instruction is D...
      --$c < 1 ? $c = 1 : 0; // Decrement ladder position, if under 1 set to 1
    } else {                 // If instruction is anything else (in this case R)
      $c = 1;                // Reset ladder position
    }
    if ($c > $h) {           // If ladder position is larger than height...
      return $i;             // Return current instruction index
    }
  }
}

daavko

Posted 2016-03-01T20:32:01.117

Reputation: 824

1

PHP, 113 bytes

Smaller version of https://codegolf.stackexchange.com/a/74575/13216

function r($h,$s){$i=0;$c=1;while($x=$s[$i++]){$c+=($x=='U'?1:($x=='D'?($c>1?-1:0):1-$c));if($c>$h){return $i;}}}

Ungolfed:

// $h - height of ladder; $s - instructions
function r($h,$s) {
    $i = 0;
    $c = 1;
    while ($x = $s[$i++]) {
        $c += (
            $x=='U'?
                1
            :
                (
                    $x=='D'? (
                        $c>1?
                            -1
                        :
                            0
                    ):
                        1-$c
                )
        );
        if ($c > $h) {
            return $i;
        }
    }
}

RibeiroBreno

Posted 2016-03-01T20:32:01.117

Reputation: 15

2Great first post! I edited your post for better readability. Happy golfing! – GamrCorps – 2016-03-02T04:42:26.293

1

Java, 250 bytes

int cmds(int n, String s) {
int steps=1;
int count=0;
for (int i=0;i< s.length();i++) {
count++;
char c=s.charAt(i);
switch(c){
case 'D':
steps=(steps==1)?1:--steps;
break;
case 'R':
steps=1;
break;
case 'U':
++steps;
break;
}
if(steps>n)
return count;
}
return 0;
}

Surya Vattikuti

Posted 2016-03-01T20:32:01.117

Reputation: 11

2When answering a [tag:code-golf]-challenge, you should start your answer with # <language_name>, XX bytes. Also you can reduce your variable names to one character each and remove extra whitespaces, this way your byte count will reduce (which is the objective here)... Ah, and welcome to PPCG! – removed – 2016-03-02T11:47:08.340

Some tips: To indent your code as code add 4 spaces at the line's start. You removed some spaces, but you can still remove more (ex: instead of int steps=1; int count=0; you can use int s=1,c=0; - look I changed the variable name - and so on). You can still show your ungolfed version below the golfed version with an explanation (this way is easy for someone help you golfing more bytes). – removed – 2016-03-02T14:39:16.673

1

Mathematica, 114 120 bytes

(d=#~Max~1-1&;u=#+1&;r=1&;s=StringToStream@ToLowerCase@#;l=1;t=1;While[(l=ToExpression[s~Read~Character]@l)<=#2,t++];t)&

Anonymous function, which takes the two arguments (C,N). Careful using this, as it doesn't close the stream it opens. Also it assigns all its variables globally.

Edited to replace d=#-1& with d=#~Max~1-1&, so that robie doesn't go digging.

hYPotenuser

Posted 2016-03-01T20:32:01.117

Reputation: 707

Wait: I don't think this is valid. It allows the robot to go down negative rungs. Whoops. That'll teach me to test non-comprehensively... I'll put a corrected one up when I get the chance. – hYPotenuser – 2016-03-03T03:07:09.313

1

Pyth, 19 bytes

x.u@[tWNNhN00)CYz0Q

Try it online: Demonstration or Test Suite

Explanation:

x.u@[tWNNhN00)CYz0Q   implicit: z = input string, Q = input number
 .u             z0    reduce z: for each char Y in z manipulate N = 0 with:
    [        )           create a list with
     tWNN                  * N-1 if N>0 else N
         hN                * N+1
           0               * 0
            0              * 0
   @          CY         replace N by the ord(Y)-th element (mod 4)
 .u                   .u give us a list with all intermediate values of N
x                 Q   print the index of Q in this list

Jakube

Posted 2016-03-01T20:32:01.117

Reputation: 21 462

1

C, 91 bytes

No warnings with gcc -Wall. Recursion and comma-separated expressions.

r.c contains bare function:

int r(int N,int n,int s,char*C){return*C&&s<=N?s+=*C&2?-s:*C&1?1:-1,r(N,n+1,s?s:1,C+1):n;}

Commented,

int r(int N,   // number of steps on ladder
      int n,   // result, seed with 0
      int s,   // current step, seed with 1
      char *C  // command string
      )
{
    return *C&&s<=N ?  // still reading commands and still on ladder?
       s+=                // increment step value by...
        *C&2?             // bit test if 'R' but not 'U' or 'D'.
         -s               // negate to 0, will set to 1 in call if needed
         :*C&1?           // Not 'R', is it 'U'?
            1             // 'U', add 1
            :-1,          // Must be 'D', subtract 1
       r(N,n+1,s?s:1,C+1) // Recursive call, and fix case where s==0.
      :n;                 // end of string or fell off ladder
}

For reference,

'U'.charCodeAt(0).toString(2)
"1010101"
'D'.charCodeAt(0).toString(2)
"1000100"
'R'.charCodeAt(0).toString(2)
"1010010"

roboladder.c wrapper,

#include <stdio.h>
#include <stdlib.h>
#include "r.c"
int main(int argc, char * argv[])
{
  int N = atoi(argv[1]);
  int n = r(N,0,1,argv[2]);
  int check = atoi(argv[3]);
  printf("%d : %d\n", n, check);
  return 0;
}

Makefile for testing,

run:
    @gcc -Wall robotladder.c -o robotladder 
    @./robotladder 1 U 1
    @./robotladder 1 DDRUDUU 4  
    @./robotladder 4 UDDUUUUURUUUUDDDD 7
    @./robotladder 4 UDDUURUUUUUUUDDDD 10
    @./robotladder 6 UUUUUDRUD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UUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU 872
    @wc -c r.c

jamieguinan

Posted 2016-03-01T20:32:01.117

Reputation: 381

1

Mathematica, 112 Bytes

i=0;First@Position[ToExpression["{"<>#~StringReplace~{"U"->"i++,","D"->"i=i~Max~1-1,","R"->"i=0,"}<>"0}"],#2-1]&

A Simmons

Posted 2016-03-01T20:32:01.117

Reputation: 4 005

0

Clojure, 92 84 bytes

Counts n to zero instead zero to n, can utilize take-while pos?.

#(count(take-while pos?(reductions(fn[p o](if o(min(o p 1)%)%))%(map{\U -\D +}%2))))

Original:

#(count(take-while(partial > %)(reductions(fn[p o](if o(max(o p 1)0)0))0(map{\U +\D -}%2))))

Maps 2nd argument U to +, D to - and others to nil. Reducing function runs (operand position 1) with non-null operand and 0 otherwise. Takes values until we are higher than the 1st input argument and counts how many we've got.

NikoNyrh

Posted 2016-03-01T20:32:01.117

Reputation: 2 361

0

Mathematica, 67 bytes

(p=i=0;While[p<#,p=Switch[#2[[++i]],"U",p+1,"D",1~Max~p-1,_,0]];i)&

Unnamed functions of two arguments, a positive integer and a list of characters, that returns a positive integer. A more straightforward While implementation than the other Mathematica entries, that manages to result in a more competetive length.

Greg Martin

Posted 2016-03-01T20:32:01.117

Reputation: 13 940