## 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 UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU -> 872

• Related – Peter Taylor Mar 1 '16 at 20:50
• I'm disappointed the task isn't to generate that ASCII art. – user253751 Mar 2 '16 at 2:34
• @immibis You know what to do... – Martin Ender Mar 2 '16 at 12:31
• Instead of a string, can we take a list of character codes? – Cyoce Mar 3 '16 at 3:04
• @Cyoce Only if your language has no other means to represent a string. – Zgarb Mar 3 '16 at 3:57

## CJam, 2625 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.
{         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.

• Good idea to process all commands even after the explosion. I'll borrow that to save a few bytes – Luis Mendo Mar 1 '16 at 22:36

# 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

• Nice 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 Mar 2 '16 at 22:06
• @Josh. I've updated. :) – removed Mar 3 '16 at 13:00
• Awesome! You can also save a couple characters by playing around with the type declarations in your function: codegolf.stackexchange.com/a/40266/13877 – Josh Mar 3 '16 at 13:43
• @Josh. Wow this is awesome! thanks – removed Mar 3 '16 at 14:19

# 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="UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU" /><br />
<button onclick="result.textContent=solution(+N.value)(C.value)">Go</button>
<pre id="result"></pre>

# 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


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

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.

• Nice job with the combination of named arguments and composition/currying – Cyoce Mar 3 '16 at 2:23

# JavaScript (ES6), 65 bytes

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

• – ETHproductions Mar 1 '16 at 21:28
• I think 0,i=0 can be changed to i=0 – Cyoce Mar 3 '16 at 0:29
• @Cyoce hmm, fails for me in a new tab (works on this page b/c i is already defined) – Charlie Wynn Mar 3 '16 at 14:04
• @CharlieWynn sorry, got my precedence mixed up – Cyoce Mar 3 '16 at 18:18

# 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
f1)q          % find first position equal to that, and subtract 1.
% Implicitly display


# 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 :)

• 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 Mar 2 '16 at 5:15

## 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 # 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

• 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 Mar 2 '16 at 2:23
• @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 Mar 2 '16 at 3:55
• 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 Mar 3 '16 at 9:48
• @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 Mar 3 '16 at 15:09
• @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 Mar 3 '16 at 15:57

# 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.
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)

# 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

• Notices are fine, as long as the code can still be run. – Zgarb Mar 2 '16 at 19:44

# 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

• Welcome 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 Mar 1 '16 at 23:39
• Corrected by forming into function, I was using interpreter when I wrote it. – Alex Burge Mar 1 '16 at 23:48
• Thank you! You should also add a header of the form ## Python, <N> bytes to show others your score. – Zgarb Mar 1 '16 at 23:58
• I don't think there can be an unnamed function. – user48538 Mar 2 '16 at 8:08
• You can save bytes by replacing 0 if x==0 else x-1 with x and x-1 – Cyoce Mar 3 '16 at 0:22

# 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!

• 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 Mar 3 '16 at 3:55

# 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


Test cases:

assert f('U', 1) == 1
assert f('DDRUDUU', 1) == 4
assert f('UDDUUUUURUUUUDDDD', 4) == 7
assert f('UDDUURUUUUUUUDDDD', 4) == 10
assert f('UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU', 354) == 872


# 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 } } }  # 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;
}
}
}

• Great first post! I edited your post for better readability. Happy golfing! – GamrCorps Mar 2 '16 at 4:42

# 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


## 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;
}

• When answering a 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 Mar 2 '16 at 11:47
• 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 Mar 2 '16 at 14:39

# 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
)
{
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,          // 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:
@wc -c r.c


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

• 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 Mar 3 '16 at 3:07

# Mathematica, 112 Bytes

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


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

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