# Question
Title: Write an interpreter for my esoteric language Jumper
I have thought up esoteric language Jumper. Later you will see why.

* It operates with random-access-memory with bytes as cells. RAM is zero indexed and initially filled with zeros.
* When trying access cells with negative indexes error should be displayed and program terminated.
* When trying read at larger index than last, zero should be returned.
* When trying write at larger index than last, RAM should be increased to multiple of 1024 and new cells filled with zeros (technically you can increase RAM not to multiple of 1024, reason was performance boost, so if it costs you a lot of characters you can do it not to multiple of 1024).
* Program also has pointer to cell in RAM which initially is zero
* When program starts executing a prompt for input string should be displayed (or take input from command line arguments, it's up to you). Input string should not contain null character (zero byte). Then input string is written to RAM starting at zero index.
* When program ends executing a box with program output is displayed - contents of RAM from zero index to first zero byte excluding.

Now, most interesting part, syntax.

Program consists of commands (unary operators-prefixes) and their arguments. Commands and arguments may be delimited with spaces or new lines but not necessary. However spaces inside arguments are invalid, for example, `# 2 = 4` is valid, but `# 2 = 4 4` is not.
Program can have comments between `()`. Comments can't be nested - for example, in `(abc(def)ghi)` comment is `(abc(def)`. Comments can be placed anywhere.

* `#123` sets RAM pointer to 123 (any positive decimal integer or zero).
* `>123` increments RAM pointer by 123 (any positive decimal integer).
* `<123` decrements RAM pointer by 123 (any positive decimal integer).
* `=123` writes 123 (any unsigned 8-bit decimal integer) in current cell.
* `+123` adds 123 (any unsigned 8-bit decimal integer) to current cell (modulo 256).
* `-123` subtracts 123 (any unsigned 8-bit decimal integer) from current cell (modulo 256).
* `:123` \- "goto" - goes to command number 123 (first is 0). You can control flow of your program only with goto's - it has to jump - that's why I decided to call this language Jumper.

If argument is missing - think of it is 1 for `><+-` commands or 0 for `#=:` commands.

Also, there is command modifier - `?` (prefix to command), it executes next command only if current cell is not zero, else skips that command. Can be applied to any command.
For example, `?:17` \- goes to command 17 if current cell is not zero.

If program is invalid or error occurs during runtime can be displayed message "Error". Because of this is CodeGolf, such short message will be fine.

# Your task

Write shortest interpreter for this language.

# Some test programs

```
(prints "Hello world!" regardless of input)
=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=

(appends "!" to the end of input string)
?:2 :4 >1 :0 =33 >1 =0

```

# Answer
> 7 votes
## Ruby, 447 bytes

```
p,i=$*
l=(i||'').length
r=[0]*l
l.times{|j|r[j]=i[j].ord}
i=j=0
s=p.gsub(/\(.*?\)|\s/,'')
q=s.scan(/(\?)?([#<>=+:-])(\d*)/)
e=->{abort"Error"}
p[/\d\s+\d/]||q*''!=s ?e[]:(r+=[0]until i+1<r.length
c=q[j]
j+=1
f=c[1]
c[0]&&r[i]==0?next: a=c[2]==''? '><+-'[f]?1:0:c[2].to_i
'=+-'[f]&&a>255?e[]: f==?#?i=a :f==?>?i+=a :f==?<?i-=a :f==?=?r[i]=a :f==?+?r[i]+=a :f==?-?r[i]-=a :j=a
i<0?e[]:r[i]%=256)while j<q.length
puts r.first(r.index 0).map(&:chr)*''

```

Takes both the program and the input via command line arguments.

**EDIT:** Fixed a few bugs, and added support for invalid syntax at the cost of 40 bytes (while adding a few other optimisations).

# Answer
> 6 votes
**Ruby 2 - ~~540~~ ~~447~~ 420 characters**
Run as " ruby2.0 jumper.rb 'instructions' 'initialization data' ". 1.x Ruby won't work (no String.bytes method).

Added multi-line commands and comments and improved my putting.

```

i=$*[0].gsub(/\([^)]*\)/m,' ').scan(/(\??)\s*([#=:><+-])\s*(\d*)/m).map{|a|[a[0]!='?',a[1],a[2]==''?/[#=:]/=~a[1]?0:1:a[2].to_i]}
N=i.size
d=$*[1].bytes
r=p=0
while p<N
u,o,x=i[p]
p+=1
d[r]=0 if d[r].nil?
case o
when'#';r=x
when'>';r+=x
when'<';r-=x
when/[=+-]/;eval "d[r]#{o.tr'=',''}=x";d[r]%=256
when':';p=x;abort'Error'if p>=N
end if u||d[r]>0
abort'Error'if r<0
end
printf"%s\n",d.take_while{|v|v&&v!=0}.pack('C*')

```

Here's a test suite with some scatter-shot tests. The easiest way to use it is to stuff the code into t/jumper.t and run "perl t/jumper.t".

```

#/usr/bin/perl
use strict;
use warnings;
#       timestamp: 2014 August 3, 19:00
#
# - Assume program takes machine code and initialization string as command
#       line options.
# - Assume all required errors reported as "Error\n".
# - Go with the flow and suffix output with \n. Merged terminal newlines are
#       unacceptable [I'm talkin' to YOU Ruby puts()!].
# - As per OP - jumping to > end-of-program must be an error.

use Test::More qw(no_plan);
# use Test::More tests => 4;

my $jumper = "jumper.rb";
#
#       "happy" path
#
# starter tests provided by OP
is( `$jumper '=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=' '' 2>&1`, "Hello world!\n", "hello world (from user2992539)");
is( `$jumper '?:2 :4 >1 :0 =33 >1 =0' 'a' 2>&1`, "a!\n", 'append !, #1 (from user2992539)');

# simple variations
is( `$jumper '?:2 :4 >1 :0 =33 >1 =0' '' 2>&1`, "!\n", 'append !, #2');
is( `$jumper '?:2 :4 >1 :0 =33' '' 2>&1`, "!\n", 'append !, #3, no NUL');

# comment delimiters don't nest
is( `$jumper "(()=" 'oops' 2>&1`, "\n", "() don't nest");
# comments and termination
is( `$jumper '(start with a comment)?(comment w/ trailing sp) # (comment w/ surrounding sp) 1 =98' 'a' 2>&1`, "ab\n", 'walk to exit');
is( `$jumper '(start with a comment)? (comment w/ leading sp)= (comment w/ surrounding sp) 97()' '' 2>&1`, "\n", 'skip to exit');
is( `$jumper '#1=0 (actually two instructions, but it scans well) :5 #=(truncate further if not jumped over)' 'a b' 2>&1`, "Error\n", 'truncate & jump to exit');

# is RAM pointer initialized to 0?
is( `$jumper '-103(g-g) ?:1025(exit) =103 #4=10' 'good' 2>&1`, "good\n\n", 'intial string in right place?');

# TBD, do jumps work?
# TBD, do conditional jumps work?
# jump right to a harder case, copy byte 0 to byte 3 and format, e.g. input="Y" output="Y=>Y"
is( `$jumper '#1=61#2=62#4=0#3=#10=#(11:)?:13:20(13:)#3+#10+#0-:11(20:)#10(21:)?:23:28(23:)#0+#10-:21(28:)#' 'Y' 2>&1`, "Y=>Y\n", 'copy a byte');

# test memory allocation by dropping 255s at increasingly large intervals
is( `$jumper '#16=511 #64=511 #256=511 #1024=511 #4096=511 #16384=511 #65536=511 #262144=511 #1048576=511 #65536-255 (20:)?:23(exit) #=' 'wrong' 2>&1`, "\n", 'test alloc()');

# upcase by subtraction
is( `$jumper '-32' 't' 2>&1`, "T\n", 'upcase via subtraction');
# 2 nested loops to upcase a character, like so: #0=2; do { #0--; #1=16; do { #1--; #2--; } while (#1); } while (#0);
is( `$jumper '#=2 (2:)#- #1=16 (6:)#1- #2- #1?:6 #0?:2 #=32 #1=32' '  t' 2>&1`, "  T\n", 'upcase via loops');
# downcase by addition
is( `$jumper '+32' 'B' 2>&1`, "b\n", 'downcase via addition');
# same thing with a loop, adjusted to walk the plank instead of jumping off it
is( `$jumper '#1 ?:3 :7 -<+ :0 #' 'B ' 2>&1`, "b\n", 'downcase via adder (from  Sieg)');
# base 10 adder with carry
is( `$jumper '#0-48#10=9#11=#5=#0(9:)?:11:22(11:)#10?:14:22(14:)-#11+#5+#0-:9(22:)#0?:110#11(25:)?:27:32(27:)#0+#11-:25(32:)#0+48>-43?:110=43>-48#10=9#11=#2(45:)?:47:58(47:)#10?:50:58(50:)-#11+#5+#2-:45(58:)#2?:110#11(61:)?:63:68(63:)#2+#11-:61(68:)#2+48>-61?:110=61>?:110=32#10=9#11=#5-10(83:)?:85:94(85:)#10?:88:94(88:)-#11+#5-:83(94:)#5?:99#4=49:100(99:)+10(100:)#11(101:)?:103:108(103:)#5+#11-:101(108:)#5+48' '1+1=' 2>&1`, "1+1= 2\n", 'base 10 adder, #1');
is( `$jumper '#0-48#10=9#11=#5=#0(9:)?:11:22(11:)#10?:14:22(14:)-#11+#5+#0-:9(22:)#0?:110#11(25:)?:27:32(27:)#0+#11-:25(32:)#0+48>-43?:110=43>-48#10=9#11=#2(45:)?:47:58(47:)#10?:50:58(50:)-#11+#5+#2-:45(58:)#2?:110#11(61:)?:63:68(63:)#2+#11-:61(68:)#2+48>-61?:110=61>?:110=32#10=9#11=#5-10(83:)?:85:94(85:)#10?:88:94(88:)-#11+#5-:83(94:)#5?:99#4=49:100(99:)+10(100:)#11(101:)?:103:108(103:)#5+#11-:101(108:)#5+48' '9+9=' 2>&1`, "9+9=18\n", 'base 10 adder, #2');

# order of assignment shouldn't affect order of print
is( `$jumper '#1=98 #0=97' '' 2>&1`, "ab\n", 'print order != assignment order');

# are chars modulo 256?
is( `$jumper '#10(#10 defaults to 0) +255+(#10 += 256) ?#(skip if #10==0) =' 'good' 2>&1`, "good\n", 'memory values limited to 0<x<255');
# go for the cycle;
is( `$jumper '(0:)+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ (256:)#4=10' 'BCID' 2>&1`, "ACID\n\n", 'cycle character less 1, PC>255');
# same thing with a loop;
is( `$jumper '#4=255(#4 = 255) (2:)#1+(#1++) #4-(#4--) ?:2(loop 255 times) #4=10(#4 = NL)' 'ADID' 2>&1`, "ACID\n\n", 'cycle character less 1, PC>255');

#       Exercise the program counter.
# PC > 255;
is( `$jumper '(0:)= (1:)############################################################################################################################################################################################################################################################### (256:)?:259 (257:)+ (258:):1 (259:)=97#3=10' 'a==' 2>&1`, "a==\n\n", 'program counter range >255');

#
#       "sad" path
#
#       Error checking required by the specification.
#
# simplest test case of PC going out of bounds
is( `$jumper ':2' '' 2>&1`, "Error\n", 'program counter too big by 1');
is( `$jumper ':1024' '' 2>&1`, "Error\n", 'program counter in space');
is( `$jumper ':1073741824' '' 2>&1`, "Error\n", 'program counter in hyperspace');
# try to drive program counter negative, if 32-bit signed integer
is( `$jumper ':2147483648(exit)' 'ridiculous speed' 2>&1`, "Error\n", 'program counter goes negative?, #1');
# try to drive program counter negative, if 64-bit signed integer
is( `$jumper ':9223372036854775808 (exit)' 'ludicrous speed' 2>&1`, "Error\n", 'program counter goes negative?, #2');

# spaces not allowed in operand; error or silently ignore (my choice)
isnt(`$jumper '#= #= #= #= #= +1 4 ' 'aops' 2>&1`, "oops\n", 'do not accept spaces in operands');
# ditto w/ a comment ; error or silently ignore (my choice)
isnt(`$jumper '#= #= #= #= #= +1(not valid)4 ' 'aops' 2>&1`, "oops\n", 'do not accept spaces in operands');

# RAM pointer error-checking; "Error" or "" are OK
isnt( `$jumper '<>=' 'oops' 2>&1 | grep -v Error`, "oops\n", 'unused negative RAM pointer behavior unspecified');
# RAM pointer negative and use it
is( `$jumper '<=' '' 2>&1`, "Error\n", 'cannot use negative RAM pointer, #1');
# check for RAM pointer wrap-around
is( `$jumper '<=' '0123456789' 2>&1`, "Error\n", 'cannot use negative RAM pointer, #2');

# The way I read this
#       "Commands and arguments may be delimited with spaces or new lines but
#       not necessary."
# multi-line commands are legit.
is( `$jumper "#4#?\n=" 'oops' 2>&1`, "\n", 'multi-line commands allowed');

# Multi-line comments would be consistent with multi-line commands, but I can't
# find something I can translate into a "must" or "must not" requirement in
#       "Program can have comments between (). ... Comments can be placed
#       anywhere."
# Until uncertainty resolved, no test case.

#
#       "bad" path
#
#       These tests violate the assumption that the instruction stream is wellll-farmed.
#
# characters not in the language; error or (my choice) silently skip
isnt(`$jumper 'x =' 'oops' 2>&1`, "oops\n", 'opcode discrimination');
# is ? accepted as an operator (vs operation modifier); error or (my choice) silently skip
is(`$jumper '(bad 0, good 0:)??0 (bad 1, good 0:):3 (bad 2, good 1:)#0' '' 2>&1`, "Error\n", '? not accepted as an opcode');

exit 0;

```

Ungolfed version.

```

#
#       Turing Machine Mach 2.0.
#       Tape? Tape? We don't need no stinkin' tape! We gots RAM!
#
#       dM = data memory
#       iM = instruction memory
#       pC = program counter
#       rP = RAM pointer
#       u, o, x = current instruction being executed
#
#       N = number of instructions in instruction memory
#

#       instruction decoder
iM = $*[0].gsub(/\([^)]*\)/m,' ').scan(/(\??)\s*([#=:><+-])\s*(\d*)/m).map { |a|
    [
        a[0] != '?',
        a[1],
        (a[2] == '')  ?  (/[#=:]/ =~ a[1] ? 0 : 1)  :  a[2].to_i
    ]
}
pC = 0
N = iM.size

dM = $*[1].bytes
rP = 0

while pC < N do
    #   u, unconditional instruction,   execute if true || (dM[rP] > 0)
    #                                   skip if false && (dM[rP] == 0)
    #   o, operator
    #   x, operand
    (u, o, x) = iM[pC]
    pC += 1
    dM[rP] = 0  if dM[rP].nil?
    if u || (dM[rP] > 0)
        case o
        when '#'
            rP = x
        when '>'
            rP += x
        when '<'
            rP -= x
        when /[=+-]/
            eval "dM[rP]#{o.tr'=',''}=x"
            dM[rP] %= 256
        when ':'
            pC = x
            abort 'Error'  if pC >= N
        end
    end
    abort 'Error'  if rP < 0
end
printf "%s\n", dM.take_while{|v|v&&v!=0}.pack('C*')

```

A quickie proto-assembler.

```

#
#       Jumper "assembler" - symbolic goto labels.
#
# what it does:
#       - translates labels/targets into absolute position
#               @label ?:good_exit
#               ...
#               :label
#
#       - a label is [a-zA-Z][a-zA-Z0-9_]*
#       - a target is @label
#       - one special label:
#               - "hyperspace" is last instruction index + 1
#       - strips out user comments
#               - everything from "//" to EOL is stripped
#               - jumper comments are stripped
#       - adds "label" comments of the form "(ddd:)"
# limitations & bugs:
#       - multi-line jumper comments aren't alway handled gracefully
#       - a target not followed by an instruction will reference
#               the previous instruction. this can only happen
#               at the end of the program. recommended idiom to
#               avoid this:
#                       @good_exit #
# what it doesn't do:
#       - TBD, simple error checking
#               - labels defined and not used
#       - TBD, symbolic memory names
#
# Example:
#
#   input -
#       (
#               adder from Sieg
#       )
#       @loop_head # 1  // while (*(1)) {
#       ?:continue
#       :good_exit
#
#       @continue -     //     *(1) -= 1;
#       <-           //     *(0) += 1;
#       +
#       :loop_head      // }
#       @good_exit #
#
#   output -
#       (0:) #1 ?:3 :7 (3:) - < + :0 (7:)#

rawSource = ARGF.map do |line|
  line.gsub(/\([^)]*\)/, ' ')   # eat intra-line jumper comments
    .gsub(/\/\/.*/, ' ')        # eat C99 comments
    .gsub(/^/, "#{$<.filename}@#{$<.file.lineno}\n") # add line ID
end.join
rawSource.gsub! /\([^)]*\)/m, '' # eat multi-line jumper comments
#
# Using example from above
#
# rawSource =
#       "sieg.ja@1\n \n" +
#       "sieg.ja@4\n@loop_head # 1\n"
#       ...
#       "sieg.ja@12\n@good_exit # \n"

instructionPattern = %r{
    (?<label> [[:alpha:]]\w* ){0}
    (?<operator> \??\s*[#=:><+-]) {0}
    (?<operand> \d+|[[:alpha:]]\w* ){0}

    \G\s*(@\g<label>\s*)?(\g<operator>\s*)?(\g<operand>)?
  }x
FAIL = [nil, nil, nil]
instructionOffset = 0
iStream = Array.new
target = Hash.new
targetComment = nil
for a in rawSource.lines.each_slice(2) do
  # only parse non-empty lines
  if /\S/ =~ a[1]
    m = nil
    catch( :parseError ) do
      chopped = a[1]
      while m = instructionPattern.match(chopped)
        if m.captures.eql?(FAIL) || (!m[:operator] && m[:operand])
          m = nil
          throw :parseError
        end
        if m[:label]
          if target.has_key?(m[:label].to_sym)
            printf $stderr, a[0].chomp + ": error: label '#{m[:label]}' is already defined"
            abort a[1]
          end
          target[ m[:label].to_sym ] = instructionOffset
          targetComment = "(#{instructionOffset}:)"
        end
        if m[:operator]
          iStream[instructionOffset] = [
              targetComment,
              m[:operator],
              /\A[[:alpha:]]/.match(m[:operand]) ? m[:operand].to_sym : m[:operand]
            ]
          targetComment = nil
          instructionOffset += 1
        end
        chopped = m.post_match
        if /\A\s*\Z/ =~ chopped
          # nothing parseable left
          break
        end
      end
    end
    if !m
      printf $stderr, a[0].chomp + ": error: parse failure"
      abort a[1]
    end
  end
end

# inject hyperspace label
target[:hyperspace] = instructionOffset

# replace operands that are labels
iStream.each do |instruction|
  if instruction[2]
    if !(/\A\d/ =~ instruction[2]) # its a label
      if target.has_key?(instruction[2])
        instruction[2] = target[instruction[2]]
      else
        abort "error: label '@#{instruction[2]}' is used but not defined"
      end
    end
  end
  puts instruction.join
end

```

# Answer
> 5 votes
## Python (729)

```
import re,sys
R,p,i,T,q,g=[0]*1024,0,0,re.findall(r'\d+|[()#><=+:?-]',sys.argv[1]),lambda i:0<=i<len(T),lambda i,d:int(T[i])if q(i)and T[i].isdigit()else d
def z(p):
 global R;assert p>=0
 if p>=len(R):R+=[0]*1024
s=sys.argv[2]
R[0:len(s)]=map(ord,s)
while i<len(T):
 t=T[i]
 if t=='(':
  while T[i]!=')':i+=1
  i+=1
  if not q(i):break
  t=T[i]
 i+=1
 if t=='#':p=g(i,0)
 if t=='>':p+=g(i,1)
 if t=='<':p-=g(i,1)
 if t=='=':z(p);R[p]=g(i,0)
 if t=='+':z(p);R[p]+=g(i,1);R[p]%=256
 if t=='-':z(p);R[p]-=g(i,1);R[p]%=256
 if t==':':
  v=int(T[i])
  i,c=-1,-1
  while c!=v:i+=1;c+=T[i]in'#><=+-:'
 if t=='?':
  assert p>=0
  if p<len(R)and R[p]==0:i+=1
 i+=q(i)and T[i].isdigit()
print''.join(chr(int(c))for c in R).split('\0')[0]

```

As for running the program:

* 1st argument: Jumper code
* 2nd argument: Initialization string

Example:

```
$ python jumper.py "=97>>(this is a comment)=98>2=99#" "xyz123"
ayb1c3

```

There are probably a few things I overlooked, so please leave a comment if you happen to try something that should work but doesn't. Note that this is written in Python 2.x code.

# Answer
> 3 votes
# CoffeeScript (465)

The first prompt box is for the program and the second prompt box is input. Test it at http://coffeescript.org.

**Original**:

```
p=prompt().replace(/\(.*?\)|[\s\n\r]/g,"").match(/\??[^\d]\d*/g) ?[]
y=p[..]
i=prompt()
r=[].map.call i,(c)->c[0].charCodeAt()
n=0
m=[(d)->n=d
(d)->m[5] (r[n]+d)%%256
(d)->p=y[d..]
(d)->m[1] -d
(d)->n-=d
(d)->r[n]=d
(d)->n+=d]
while b=p.shift()
 if b[0]=="?"
  continue unless r[n]
  b=b[1..]
 d="><+-#=:".indexOf(b[0])//4
 ~d||throw "!badcmd '#{b[0]}'"
 m[b[0].charCodeAt()%7](+b[1..]||+!d)
 n<0&&throw "!ramdix<0"
alert String.fromCharCode(r...).replace(/\0.*/,"")

```

This is still golfed, but commented:

```
# Get program
p=prompt().replace(/\(.*?\)/g,"").match(/\??[^\s\d]\d*/g) ?[]
# Create a copy of the program (for goto)
y=p[..]
# Get input
i=prompt()
# Put the input in the ram
r=[].map.call i,(c)->c[0].charCodeAt()
# RAM pointer
n=0
# An array of commands
# Since each of "<>+-#=:" is a different
# value mod 7 (what a coincedence?!)
# So 0th value is "#" command because
# "#".charCodeAt() % 7 === 0
m=[(d)->n=d
(d)->m[5] (r[n]+d)%%256
(d)->p=y[d..]
(d)->m[1] -d
(d)->n-=d
(d)->r[n]=d
(d)->n+=d]
# Iterate through commands
while b=p.shift()
 # If you find a "?" skip unless r[n] is > 0
 if b[0]=="?"
  continue unless r[n]
  b=b[1..]
 # Get the default value
 d="><+-#=:".indexOf(b[0])//4
 # If the command isn't good, throw an error
 throw "!badcmd '#{b[0]}'" if d==-1
 # Call the appropriate command
 # By computing the char code mod 7
 m[b[0].charCodeAt()%7](+b[1..]||+!d)
 # Make sure n is bigger than or equal to 0
 throw "!ramdix<0" if n<0
# Show output
alert String.fromCharCode(r...).replace(/\0.*/,"")

```

**Edit**: Adding spaces took more bytes than I thought. This interpreter will throw an error on invalid syntax, the other has unspecified behavior on invalid syntax.

```
p=prompt().replace(/\(.*?\)/g,"").match(/\??[^\d\s\r\n]\s*\n*\r*\d*/g) ?[]
y=p[..]
i=prompt()
r=[].map.call i,(c)->c[0].charCodeAt()
n=0
m=[(d)->n=d
(d)->m[5] (r[n]+d)%%256
(d)->p=y[d..]
(d)->m[1] -d
(d)->n-=d
(d)->r[n]=d
(d)->n+=d]
while b=p.shift()?.replace /^(.)(\s\r\n)*/,"$1"
 if b[0]=="?"
  continue if !r[n]
  b=b[1..]
 d="><+-#=:".indexOf(b[0])//4
 ~d||throw "!badcmd"
 m[b[0].charCodeAt()%7](+b[1..]||+!d)
 n<0&&throw "!ramdix<0"
alert String.fromCharCode(r...).replace(/\0.*/,"")

```

# Answer
> 2 votes
## Clojure - ~~585~~ 577 bytes

```
Edit:   I forgot modulo 256, of course
Edit 2: Now supports whitespace and comments anywhere. (585 -> 578)

```

No special golfing tricks used, because I don't know any for Clojure. The interpreter is purely functional. Comes packed with a nice error message in case of negative RAM address (an error is outputted, but no exceptions or errors are thrown).

```
(defn j[o i](let[o(re-seq #"\??[#<>=+:-]\d*"(clojure.string/replace o #"\(.*?\)|\s"""))r(loop[c 0 p 0 m(map int i)](if-let[f(nth o c nil)](let[[c p m]((fn r[t](let[f(first t)s(if(next t)(apply str(next t))(case f(\#\=\:)"0"(\>\<\+\-)"1"))v(read-string s)a(nth m p 0)](case f\?(if(=(nth m p 0)0)[c p m](r s))\#[c v m]\>[c(+ p v)m]\<[c(- p v)m]\:[(dec v)p m][c p(assoc(vec(concat m(repeat(- p(count m))0)))p(mod({\+(+ a v)\-(- a v)}f v)256))])))f)](if(< p 0)(str"Negative index "p" caused by "f)(recur(inc c)p m)))m))](if(string? r)r(apply str(map char(take-while #(> % 0)r))))))

```

Examples:

```
(j "=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=" "")
=> "Hello world!"
(j "?:2 :4 >1 :0 =33 >1 =0" "hi there")
=> "hi there!"
(j "#1 ?:3 :7 -<+ :0" "01") ; adder
=> "a"
(j "?:2 :4 >1 :0 =33 <10 =0" "hi there")
=> "Negative index -2 caused by <10"
(j "=72>=101>=108>=108>=111>=3(comment here <100)2>=119>=111>=114>=108>=100>=33>=" "")
=> "Hello world!"

```

~~Original~~ slightly ungolfed code:

```
(defn memory
  ([]
    (vec (repeat 1024 0)))
  ([m i v]
    (assoc (vec (concat m (repeat (- i (+ -1024 (mod i 1024)) (count m)) 0)))
           i v)))

(defn parse [c p m t]
  (let [f (first t)
        s (if-let [v (next t)]
            (apply str v)
            (case f
              (\#\=\:) "0"
              (\>\<\+\-) "1"))
        v (read-string s)
        a (nth m p 0)]
    (case f
      \? (if (= (nth m p 0) 0) [c p m] (parse c p m s))
      \# [c v m]
      \> [c (+ p v) m]
      \< [c (- p v) m]
      \: [(dec v) p m]
      [c p (memory m p (mod ({\+ (+ a v) \- (- a v)} f v) 256))])))

(defn jumper [o i]
  (let [o (re-seq #"\??[#<>=+:-]\d*" (clojure.string/replace o #"\(.*?\)|\s" ""))
        r (loop [c 0
                 p 0
                 m (map int i)]
            (if-let [f (nth o c nil)]
              (let [[c p m] (parse c p m f)]
                (if (< p 0)
                  (str "Negative index " p " caused by " (nth o c))
                  (recur (inc c) p m))) m))]
    (if (string? r)
      r
      (apply str (map char (take-while #(> % 0) r))))))

```

# Answer
> 2 votes
# C 496

**Edits:**

* **Thanks to @Dennis it is now much shorter (and works in GCC to boot)**
* **Thanks to @S.S.Anne for suggesting abort()**
* **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**

The golfed version

```
#define M R=realloc(R,r+Q),bzero(R+r,Q),r+=Q
#define J z<0?abort(),0:z>r
#define G J||R[z]
#define P J?M:0,R[z]
#define O!C[1]?1:V;I+23
#define I;if(*C==35
#define W;while(*p&*p<33)p++
Q=1024;char*R,C[999][9],*p,*q,*o;r,z,c,V;E(char*C){I+28)G&&E(C+1);else{V=atoi(C+1)I)z=V;I+27)z+=O+2)z-=O+3)P=V;V--I+8)P=G+O-13)P=G-O)c=V;}}main(u,v)int**v;{M;for(o=v[u-3||strcpy(R,v[2])];*o;bcopy(p,q,o-p)){p=o;q=C[c++]W;if((*q++=*p++)==63){W;*q++=*p++;}W;strtol(p,&o,0);}for(c=*C[c]=0;*C[c];)E(C[c++]);puts(R);}

```

Try it online!

A slightly less golfed version of my original program:

```
#include<stdlib.h>
#include<memory.h>
#include<string.h>
#include<stdio.h>
#define CHAR_STAR char*
#define CASTED_R (CHAR_STAR)RAM
#define UNSIGNED_CHAR unsigned char
#define INCREASE_MEMORY RAM=(UNSIGNED_CHAR*)realloc(CASTED_R,RAM_size+1024),memset(CASTED_R+RAM_size,0,1024),RAM_size+=1024
#define IF_ERROR current<0?exit(puts("!")),0:current>RAM_size?
#define GET_CELL IF_ERROR 0:RAM[current]
#define PUT_CELL(x) IF_ERROR INCREASE_MEMORY,RAM[current]=x:RAM[current]=x;
#define ONE_IF_EMPTY !*(command+1)?1:
#define VALUE atoi(command+1)
#define REMOVE_WHITESPACE while (*pointer&&*pointer<33)pointer++;
#define COPY_CHAR (*command++ = *pointer++)
#define RETURN return
char commands[999][9];
UNSIGNED_CHAR*RAM = 0;
int RAM_size = 0, current = 0, command_size = 0;
CHAR_STAR get_command(CHAR_STAR a)
{
    CHAR_STAR pointer = a, *command = commands[command_size++], *next;
    REMOVE_WHITESPACE
    if (COPY_CHAR == '?')
    {
        REMOVE_WHITESPACE
        COPY_CHAR;
    }
    REMOVE_WHITESPACE
    int i = strtol(pointer, &next, 0);
    memcpy(command, pointer, next - pointer);
    command[next - pointer] = 0;
    RETURN next;
}
void eval(CHAR_STAR command){
    if (*command == '?')RETURN GET_CELL ? eval(command + 1) : 0;
    if (*command == '#')current = VALUE;
    if (*command == '>')current += ONE_IF_EMPTY VALUE;
    if (*command == '<')current -= ONE_IF_EMPTY VALUE;
    if (*command == '=')PUT_CELL(VALUE)
    if (*command == '+')PUT_CELL(GET_CELL + ONE_IF_EMPTY VALUE - 1)
    if (*command == '-')PUT_CELL(GET_CELL - ONE_IF_EMPTY VALUE - 1)
    if (*command == ':')command_size = VALUE - 1;
}
int main(int argc, CHAR_STAR *argv)
{
    INCREASE_MEMORY;
    argc == 3 ? strcpy(CASTED_R, argv[2]) : 0;
    CHAR_STAR command = argv[1];
    while (*command) command = get_command(command);
    *commands[command_size] = 0; command_size = -1;
    while (*commands[++command_size]) eval(commands[command_size]);
    RETURN puts(CASTED_R);
}

```

# Answer
> 1 votes
## Javascript, 519

```
C=prompt().replace(/\(.*?\)/g,"").match(/\??[#><=+:-]\d*/g)
M=prompt().split("").map(function(c){return c.charCodeAt(0)})
R=0
f=function(I){T=I[0]
A=I.slice(1)
if(T=="?")return M[R]?f(A):P++
A=A==""?1:+A
if(T==">")R+=A
if(T=="<")R-=A
if("=+-".indexOf(T)+1){if(R<0)throw alert("ERR RAMidx<0")
while(R>=M.length)M.push(0)}
if(T=="+")M[R]=M[R]+A&255
if(T=="-")M[R]=M[R]-A&255
A=+I.slice(1)
if(T=="#")R=A
if(T=="=")M[R]=A
if(T==":")P=A;else++P}
for(P=0;C[P];)f(C[P])
alert(String.fromCharCode.apply(7,M).replace(/\0.*/,""))

```

This gets the program and input via prompt boxes. Pasting this in your browser's Javascript console will work, as well as throwing this in a file, pasting before the code `<!DOCTYPE html>`, newline, `<html><head><script>`, and after the code `</script></head><body></body></html>`, and saving the resulting file as "swagger.html".

This is my first attempt at this thing, and I already like the language. Kinda. It really needs text labels though, instead of this BASIC-style instruction index labeling.

Ungolfed version (kinda):

```
var C,M,R,P,f;
C=prompt().replace(/\(.*?\)/g,"").match(/\??[#><=+:-]\d*/g); //Code
M=prompt().split("").map(function(c){return c.charCodeAt(0)}); //Memory
R=0; //RAM pointer
f=function(I){ //parser function, Instruction
    var T,A;
    T=I[0]; //Type
    A=I.slice(1); //Argument
    if(T=="?")return M[R]?f(A):P++;
    A=A==""?1:+A;
    if(T==">")R+=A;
    if(T=="<")R-=A;
    if("=+-".indexOf(T)+1){
        if(R<0)throw alert("ERR RAMidx<0");
        while(R>=M.length)M.push(0);
    }
    if(T=="+")M[R]=M[R]+A&255;
    if(T=="-")M[R]=M[R]-A&255;
    A=+I.slice(1);
    if(T=="#")R=A;
    if(T=="=")M[R]=A;
    if(T==":")P=A;else++P;
}
for(P=0;C[P];f(C[P])); //Program pointer
alert(String.fromCharCode.apply(7,M).replace(/\0.*/,""));

```

# Answer
> 1 votes
# Haskell: an ungodly amount of characters

Alright, right now this is something that might or might not be golfed shortly. It is freakishly huge for what it is, with lots and lots of sloppily written code (it was quite some time since I last touched Haskell). But it was fun to write.

```
import Data.Char

parse [] p c a m i =
    if c == ' ' || c == '?' then
        []
    else
        (p ++ [(c, a, m)])

parse (h:t) p c a m i
    | i
        = parse t p c a m (h == ')')
    | isDigit h && a < 0
        = parse t p c (digitToInt h) m i
    | isDigit h
        = parse t p c (10 * a + (digitToInt h)) m i
    | elem h "#><=+-:?"
        = if c == ' ' || c == '?' then
            parse t p h a (c == '?') i
        else
            parse t (p ++ [(c, a, m)]) h (-1) False i
    | otherwise
        = case h of
            '(' -> parse t p c a m True
            ' ' -> parse t p c a m i
            _   -> []

run p pp r rp
    | pp >= length p
        = r
    | pp < 0 || rp < 0
        = []
    | otherwise
        = if mr then
            case c of
                '#' -> run p (pp + 1) r pa
                '>' -> run p (pp + 1) r (rp + pa)
                '<' -> run p (pp + 1) r (rp - pa)
                '=' -> run p (pp + 1) (rh ++ ((chr pa) : rt)) rp
                '+' -> run p (pp + 1) (rh ++ (chr (mod ((ord h) + pa) 256) : rt)) rp
                '-' -> run p (pp + 1) (rh ++ (chr (mod ((ord h) - pa + 256) 256) : rt)) rp
                ':' -> run p pa r rp
        else
            run p (pp + 1) r rp
        where
            (c, a, m)
                = p !! pp
            (rh, h:rt)
                = splitAt rp r
            pa
                = if a < 0 then
                    if elem c "><+-" then
                        1
                    else
                        0
                else
                    a
            mr
                = ord (r !! rp) > 0 || not m

main = do
    p <- getLine
    let n = parse p [] ' ' (-1) False False
    if n == []
        then do
            putStrLn "Error"
        else do
            s <- getLine
            let r = run n 0 (s ++ (repeat (chr 0))) 0
            if r == []
                then do
                    putStrLn "Error"
                else do
                    putStrLn (takeWhile (/=(chr 0)) r)

```

# Answer
> 0 votes
# Groovy 582

ungolfed version:

I think there is a bug with the comments, which are not recognized correctly, which might be caused by the stupid regex I used, but the 2 programs run as they should:

```
class P {
    def c = 0
    def p = 0
    def m = []

    P(i="") {
        m = i.chars.collect { it }
        m << 0
    }

    def set(v) { m[p] = v }
    def add(v) { m[p] += v }
    def sub(v) { m[p] -= v }

    def eval(i) {
        while(c < i.size()) {
            if (i[c].p && m[p] == 0) {c++}
            else { i[c].f(this,i[c].v) }
        }
        return m
    }
}

def parse(s) {
    def ops = [
       '#' : [{p, v -> p.p = v; p.c++}, "0"],
       '>' : [{p, v -> p.p += v; p.c++}, "1"],
       '<' : [{p, v -> p.p -= v; p.c++}, "1"],
       '=' : [{p, v -> p.set(v); p.c++}, "0"],
       '+' : [{p, v -> p.add(v); p.c++}, "1"],
       '-' : [{p, v -> p.sub(v); p.c++}, "1"],
       ':' : [{p, v -> p.c = v}, "0"]
    ]

    (s =~ /\(.*\)/).each {
        s = s.replace(it, "")
    }

    (s =~ /(\?)?([#><=+-:])([0-9]*)?/).collect {
        def op = ops[it[2]]
        [f : op[0], v : Integer.parseInt(it[3] ?: op[1]), p : it[1] != null ]
    }
}

```

# Answer
> 0 votes
# Haskell, 584

The input and jumper program are provided as the first two lines of input from stdin.

```
a g(i,n,x)=(i+1,n,take n x++((g$x!!n)`mod`256):drop(n+1)x)
b g(i,n,x)=(i+1,g n,x)
c=b.q:a.(+):g:a.(-):b.(-):a.q:b.(+):c
d=(%['0'..'9'])
e=fromEnum
f=0>1
g n(_,x,y)=(n,x,y)
h(x:_)=d x;h _=f
i g p@(j,n,m)|x$m!!n=g p|t=(j+1,n,m)
j=0:1:0:1:1:0:1:j
k=takeWhile
l[]=[];l(x:y)|x%") \n"=l y|x%"("=l$u(/=')')y|t=x:l y
main=v>>=(\y->v>>=putStr.map toEnum.k x.r(0,0,map e y++z).p.l)
o n s|h s=(read$k d s,u d s)|t=(n,s)
p[]=[];p(x:y)|x%"?"=w$p y|t=(c!!e x)n:p m where(n,m)=o(j!!e x)y
q=const
r s@(i,n,m)p|i<length p=r((p!!i)s)p|t=m
t=0<1
u=dropWhile
v=getLine
w(m:n)=i m:n
x=(/=0)
z=0:z
(%)=elem

```

I'll post an ungolfed version later, but in the meantime I wanted to leave this as a puzzle for the reader:

> Where are the jumper commands such as '#' etc?

Have fun!

# Answer
> 0 votes
# Perl 5 `-F`, 345 bytes

```
$#F--;$_=<>;s/\(.*?\)|\s*([+<>#=:?-])\s*/$1/g;die'Error'if/[^+<>#=?:0-9-]/+/\?\d/;s/[><+-]\K(?=\D|$)/1/g;s/[#=:]\K(?=\D|$)/0/g;map$_=ord,@F;@c=/.*?\d+/g;while($l<@c){$_=$c[$l++];s/\?//*!$F[$p]&&next;/[=+-]/?$F[$p]=eval"(\$F[\$p]$_)%256":/[<>]/?eval'$p=$p'.y/></+-/r:/#/?$p=y/#//dr:s/://&&($l=$_);die'Error'if$p*$l<0||$l>@c}print$_?chr:last for@F

```

Try it online!

The first line of input is the initialization of RAM, the second line is the jumper program.

---
Tags: code-golf, interpreter
---


# Question
Title: Convert from Infix Notation to Prefix Notation
Given an arithmetic expression, which can include parentheses (`()`), exponents (`^`), division (`/`) and multiplication (`*`), addition (`+`) and subtraction (`-`) (in that order of operation), such as

```
a ^ (2 / 3) * 9 * 3 - 4 * 6

```

output the same expression in prefix notation.

```
(- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))

```

Spaces are optional in the input as well as the output. You may assume that all operators are left-associative and that all of the numbers in the expression are single digit integers (i.e. `[0-9]`).

This is a code golf challenge, so the shortest solution wins.

# Answer
## Ruby 1.9 - 134

```
%w[** / * + -].map{|o|String.send(:define_method,o){|n|"(#{o=='**'??^:o} #{self} #{n})"}}
puts eval gets.gsub(/\w/,'?\0').gsub ?^,'**'

```

Pretty evil, but it works:

```
$ echo 'a ^ (2 / 3) * 9 * 3 - 4 * 6' | ruby sol.rb
(- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))

```
> 13 votes

# Answer
## Python, 222 chars

```
class A:
 def __init__(s,x):s.v=x
for x in('pow^','mul*','div/','add+','sub-'):exec('A.__'+x[:3]+'__=lambda s,y:A("('+x[3]+'"+s.v+y.v+")")')
import re
print eval(re.sub('(\\w)','A("\\1")',raw_input().replace('^','**'))).v

```

Similar to the Ruby one, except Python doesn't let you redefine the global ops, only ops of a class.
> 3 votes

# Answer
## Perl 6 (146|150)

The easiest way to do this is to just swap out the subroutines that implement the operators for new ones.

```
sub infix:«+»   ($a,$b) { "(+ $a $b)" }
sub infix:«-»   ($a,$b) { "(- $a $b)" }
sub infix:«*»   ($a,$b) { "(* $a $b)" }
sub infix:['/'] ($a,$b) { "(/ $a $b)" } # stupid highlighter
sub infix:«**»  ($a,$b) { "(^ $a $b)" }

# currently there seems to be a bug that
# prevents this from modifying the parser correctly
# probably because there is already a different operator with this name
# which has nothing to do with exponentiation
my &infix:«^» := &[**];

say 'a' ** (2 / 3) * 9 * 3 - 4 * 6;
# (- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))␤

```

The absolute minimum amount of bytes for doing it this way is:

```
sub infix:<+>{"(+ $^a $^b)"}␤  #   29
sub infix:<->{"(- $^a $^b)"}␤  # + 29
sub infix:<*>{"(* $^a $^b)"}␤  # + 29
sub infix:<**>{"(^ $^a $^b)"}␤ # + 30
sub infix:</>{"(/ $^a $^b)"}␤  # + 29

```

146 bytes, although it makes more sense to count graphemes in Perl 6.

This assumes that "*output the same expression in prefix notation*" could just refer to the result of the expression, not necessarily the output of the program.

You would have to add `say` in front of the expression to get the program to print it to STDOUT. (150 bytes)
> 1 votes

# Answer
## Unix TMG, 189 bytes

```
p:ignore(<< >>)parse(e);e:q(t,a);t:q(x,m);x:q(r,h);q:proc(x,y)x k:y/d x={<(>2 3 1<)>}b\k;r:o(!<<+-*/^()>>)|<(>e<)>;a:o(<<+->>);m:o(<<*/>>);h:o(<<^>>);o:proc(n)smark any(n)scopy;d:;b:bundle;

```

The solution is almost straight from the manual for the language, with only basic golfing.

Expanded:

```
prog:  ignore(<< >>) parse(expr);
expr:  q(term, addop);
term:  q(fact, mulop);
fact:  q(prim, expop);
q:     proc(x,y) x k: y/done x ={ <(> 2 3 1 <)> } b\k;
prim:  op(!<<+-*/^()>>) | <(> expr <)>;
addop: op(<<+->>);
mulop: op(<<*/>>);
expop: op(<<^>>);
op:    proc(n) smark any(n) scopy;
done:  ;
b:     bundle;

```
> 0 votes

---
Tags: code-golf, math
---


# Question
Title: Intersection of circles – How can I reduce this golf code to 127 bytes?
I started a CodeWars kata in Python, just two days ago, related to code golf.

Task: Given two congruent circles *a* and *b* of radius *r*, return the area of their intersection rounded down to the nearest integer, in less than 128 chars.

* Has to be a one-liner.
* Version: Python 3.6
* External libraries: You may import NumPy as an external library.
* Function name: `circleIntersection`
* Input example: `circleIntersection([0,0],[0,10], 10)`

This is the closest I could come (129):

```
from math import*;circleIntersection=lambda a,b,r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(b[0]-a[0],b[1]-a[1])/r/2)//.5

```

# Answer
## Direct translation to NumPy: 127 bytes

```
from numpy import*
circleIntersection=lambda a,b,r:r*r*(lambda h:h<1and arccos(h)-h*(1-h*h)**.5)(hypot(*subtract(b,a))/r/2)//.5

```

Try it online!

Converting your code to numpy seems to save the required bytes. While using `hypot` is still ugly, being able to splat the result of `subtract` is still enough shorter that the loss of converting to `arccos` doesn't matter.

It is possible this can save more since it doesn't error on `h<1` and will return `nan` in the case that the circles do not intersect. I don't know if that is permissible though since `nan` is not equal to zero.

I'm not convinced this is optimal, in particular I didn't look at improving the algorithm at all.
> 4 votes

# Answer
## Use Python 2's arg unpacking: 124 bytes

```
from math import*;circleIntersection=lambda(v,w),(x,y),r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(v-x,w-y)/r/2)//.5

```

Try it online!

Python 2 has parameter unpacking, allowing the input point arguments to be taken directly as pairs `(v,w)` and `(x,y)`, where the input lists like `[0,0]` and `[0,10]` will be unpacked into the respective variables. This feature was removed in Python 3 -- a pity, in my opinion, since the old syntax seems more readable. But, the site has a Python 2 option, and nothing in your solution relies on Python 3.
> 7 votes

# Answer
# Use `def`: 125 bytes

You have a classic dilemma of wanting to assign to a variable without losing the brevity of a `lambda` function. Your method of using an inner lambda for assignment is one solution. The problem site not having Python 3.8 means the walrus operator is unfortunately off limits.

But, it's shorter here to just use `def` and suck up the bytes of writing out `return`. This is generically a 7-byte cost according to this reference. Within the `def`, we can just write the statement `h=` to do the assignment. We put everything on one line separated with `;` to avoid needing to indent.

**125 bytes**

```
from math import*
def circleIntersection(a,b,r):h=hypot(b[0]-a[0],b[1]-a[1])/r/2;return(h<1and acos(h)-h*(1-h*h)**.5)*r*r//.5

```

Try it online! (vs original)

I've changed the multiplication order from `return r*r*(...)//.5` to `return(...)*r*r//.5` to cut the space after `return`.

There are likely other byte saves, including FryAmTheEggman's switch to `numpy`, but refactoring from `lambda` to `def` is already enough to get below 128 bytes.
> 5 votes

---
Tags: code-golf, tips, python
---


# Question
Title: Approximate definite integrals using Riemann sums
Left and right Riemann sums are approximations to definite integrals. Of course, in mathematics we need to be very accurate, so we aim to calculate them with a number of subdivisions that approaches infinity, but that's not needed for the purposes of this challenge. You should instead try to write the shortest program, taking input and providing output through any of the default methods, in any programming language, which does the following:

# Task

Given two rational numbers \\$a\\$ and \\$b\\$ (the limits of the definite integral), a positive integer \\$n\\$, a boolean \\$k\\$ representing left / right and a black-box function \\$f\\$, calculate the left or right Riemann sum (depending on \\$k\\$) of \\$\int\_a^b f(x)\mathrm{d}x\\$, using \\$n\\$ *equal* subdivisions.

# I/O Specs

* \\$a\\$ and \\$b\\$ can be rational / floating-point numbers or fractions.
* \\$k\\$ can be represented by any two distinct and consistent values, but please keep in mind that you aren't allowed to take complete or partial functions as input.
* \\$f\\$ is a black-box function. Citing the meta answer linked above, *the content (i.e. the code) of black-box-functions may not be accessed, you can only call them (passing arguments if applicable) and observe their output*. If needed, please include the necessary information about the syntax your language uses such that we can test your submission.

As output, you must provide a rational / floating-point / fraction representing the Riemann sum you are asked for. As discussed in the past, floating-point imprecision can be ignored, as long as your output is accurate to at least three decimal places when rounded to the nearest multiple of 1 / 1000 (e.g. `1.4529999` is fine instead of `1.453`).

# Math Specs

* \\$f\\$ is guaranteed to be continuous between \\$a\\$ and \\$b\\$ (no jumps, no holes, no vertical asymptotes).
* There are three possible cases you have to handle: \\$a = b\\$ (The result should be \\$0\\$ or its equivalents), \\$a \ b\\$.
* If \\$b \< a\\$, the integral changes its sign. Also, the right sense of the integral in this case is towards \\$a\\$.
* Areas under the graph are negative and those above the graph are positive.

# Examples / Test Cases

The resolution is not optimal, because I had to shrink them down a bit, but they're still readable.

* \\$f(x) = 2x + 1,\\: a = 5,\\: b = 13,\\: n = 4\\$, k = right:

The result should be \\$15 \cdot 2 + 19 \cdot 2 + 23 \cdot 2 + 27 \cdot 2 = 168\\$, because the width of each rectangle is \\$\frac{|b - a|}{n} = 2\\$ and the corresponding heights are \\$f(7) = 15,\\:f(9) = 19,\\:f(11) = 23,\\:f(13) = 27\\$.
* \\$f(x)=\sqrt{x},\\: a = 1,\\: b = 2.5,\\: n = 3\\$, k = left:

The output should be \\$1.8194792169\\$.
* \\$f(x) = -3x + 4 + \frac{x^2}{5},\\: a = 12.5,\\: b = 2.5,\\: n = 10\\$, k = right:

The expected output value is \\$- (- 4.05 - 5.45 - 6.45 - 7.05 - 7.25 - 7.05 - 6.45 - 5.45 - 4.05 - 2.25) = 55.5\\$, because the integral changes signs when flipping the boundaries (\\$b\<a\\$).
* \\$f(x) = 9 - 4x + \frac{2x^2}{7},\\: a = 0,\\: b = 15,\\: n = 3\\$, k = left:

Calculating our Riemann sum, we get \\$13.5714285715\\$.
* \\$f(x) = 6,\\: a = 1,\\: b = 4,\\: n = 2\\$, k = right — Output: \\$18\\$.
* \\$f(x) = x^7 + 165x + 1,\\: a = 7,\\: b = 7,\\: n = 4\\$, k = left — Output: \\$0\\$.
* \\$f(x) = x \cdot \sin(x^{-1}),\\: a = 0,\\: b = 1,\\: n = 50\\$, k = right — Output: \\$0.385723952885505\\$. Note that sine uses radians here, but feel free to use degrees instead.

# Answer
# , ~~69~~ ~~65~~ ~~63~~ 57 bytes

```
function(a,b,n,k,f,w=(b-a)/n)sum(sapply(a+w*(1:n-k),f))*w

```

Try it online!

Takes `k=FALSE` for right-hand sums, although the TIO link now includes aliases for "left" and "right" for ease of use.

`a+w*(1:n-k)` generates appropriate left- or right-hand points.

Then `sapply` applies `f` to each element of the result, which we then `sum` up and multiply by the interval width `(b-a)/n` to yield the result. This last also neatly takes care of any sign issues we might have.
> 10 votes

# Answer
# SNOBOL4 (CSNOBOL4), 127 bytes

```
	DEFINE('R(a,b,n,k,p)')
R	l =(b - a) / n
	i =1
l	R =R + eval(p '(a + l * (i - k))')
	i =lt(i,n) i + 1	:s(l)
	R =R * l :(return)

```

Try it online!

Assuming that the function `p` is defined somewhere, this takes `a,b,n,k,(name of p)`, with `k=0` for right and `l=1` for left.

catspaw's `SNOBOL4+` supports `REAL`s but doesn't have builtin trig functions. However, I suppose one could come up with a reasonable `sin` function using a taylor series.

I'm not 100% sure this is the "right" way to pass a black-box function in SNOBOL (which, to my knowledge, doesn't have first-class functions), but it seems reasonable-ish to me.

I suppose that assuming the function is defined as `f` would be shorter, as line `l` could be

```
l	R =R + f(a + l * (i - k))
```

but then it's not passed as an argument, which feels a bit like "cheating".

Note that the TIO link has a `:(e)` after the `DEFINE` statement, which is so that the code will actually run properly.
> 4 votes

# Answer
# Julia 0.6, 50 bytes

```
R(f,a,b,n,k)=(c=(b-a)/n;sum(f.(a+[k:n+k-1...]c))c)

```

Try it online!

A normalized range is constructed, collected into a vector and then scaled. Collecting the range into a vector using `[X...]` is necessary to avoid the `inexact error` when multiplying the range directly with 0 when `a=b`. Similarly, constructing a range directly with `:` or `range()` is not possible when `a=b`.

The usage of k is very similar to the solution of Guiseppe, with `k=1` for `right` and `k=0` for `left`.
> 4 votes

# Answer
# Haskell, ~~73~~ 67 bytes

Thanks to H.PWiz and Bruce Forte for the tips!

```
(f&a)b n k|d<-(b-a)/realToFrac n=d*sum(f<$>take n(drop k[a,a+d..]))

```

Try it online!

Pretty straightforward solution.

`k` is `0` for left and `1` for right.
> 2 votes

# Answer
# Jelly, 21 bytes

```
ƓḶ+Ɠ÷
IḢ×¢A+ṂɠvÐ€Æm×I

```

Try it online!

Take `a,b` from arguments, and

```
n
right
f

```

from stdin.

---

If you are not familiar with Jelly, you can use Python to write the black box function `f`:

***f(x)*** *= 2x + 1*; **a** = 5; **b** = 13; **n** = 4; **k** = right

***f(x)*** *= √x*; **a** = 1; **b** = 2.5; **n** = 3; **k** = left

***f(x)*** *= -3x + 4 + 1/5 * x2*; **a** = 12.5; **b** = 2.5; **n** = 10; **k** = right

***f(x)*** *= 9 - 4x + 2/7 * x2* ; **a** = 0; **b** = 15; **n** = 3; **k** = left

***f(x)*** *= 6*; **a** = 1; **b** = 4; **n** = 2; **k** = right

***f(x)*** *= x * sin(1 / x)*; **a** = 0; **b** = 1; **n** = 50; **k** = right

---

Explanation:

```

ƓḶ+Ɠ÷     Helper niladic link.
Ɠ         First line from stdin. (n). Assume n = 4.
 Ḷ        Lowered range (unlength). Get [0, 1, 2, 3].
  +Ɠ      Add second line from stdin (k). Assume k = 1 (right).
            Get [1, 2, 3, 4].
    ÷     Divide by (n). Get [0.25,0.5,0.75,1].

IḢ×¢A+ṂɠvÐ€Æm×I   Main monadic link. Take input `[a, b]`, assume `a=2,b=6`.
IḢ                `a-b`. Get `-4`.
  ×¢              Multiply by value of niladic link above. Get `[-1,-2,-3,-4]`.
    A             Absolute value. Get `[1,2,3,4]`.
     +Ṃ           Add min(a, b) = 2. Get `[3,4,5,6]`.
        vÐ€       For each number, evaluate with...
       ɠ            input line from stdin.
           Æm     Arithmetic mean.
             ×I   Multiply by `a-b`.

```
> 2 votes

# Answer
# Python 2, ~~99~~ 94 bytes

A bit of a naive solution.

```
def R(f,a,b,n,k):s=cmp(b,a);d=s*(b-a)/n;return s*sum(d*f([0,a,b][s]+i*d)for i in range(k,n+k))

```

**Try it online!**
> 2 votes

# Answer
# JavaScript (Node.js), ~~73~~ ~~71~~ 59 bytes

```
(a,b,n,k,f)=>(g=i=>i--&&g(i)+f(a+k++/n)/n)(n,k^=a>b,n/=b-a)

```

Try it online!
> 1 votes

# Answer
# Perl 6, 65 bytes

```
{my \d=($^b-$^a)/$^n;sum ($a,*+d...*)[($^k+^0>d)+ ^$n]».&^f X*d}

```

Try it online!

Relatively straightforward. The only complication is handling the `a > b` case, which I do by xor-ing the input flag `$^k` with `0 > d`, which inverts it when `a > b`.
> 1 votes

# Answer
# 05AB1E, 22 bytes

```
L<+¹/I`α©*³ß+Iδ.VÅA®*Ä

```

Inputs in the order \\$n\\$, \\$k\\$, \\$\[a,b\]\\$, \\$f\\$, with \\$k\\$ being `1` for right and `0` for left.

Try it online or verify all test cases.

**Explanation:**

```
L                      # Push a list in the range [1, (implicit) input n]
 <                     # Decrease each by 1 to make the range: [0, n)
  +                    # Add the (implicit) input k to each
   ¹/                  # Divide each by the first input n
     I                 # Push the next input [a,b]
      `α               # Push both separated to the stack, and take their absolute difference
        ©              # Store this in variable `®` (without popping)
         *             # Multiply it to each value in the list
          ³ß           # Push the third input [a,b] again, and pop and push its minimum
            +          # Add it to each value in the list
              δ        # Apply to each value in the list,
             I         # using the next input f:
               .V      #  Evalutate the it as 05AB1E code
                 ÅA    # Then pop and push the arithmetic mean of the list
                   ®*  # Multiply it by |a-b| from variable `®`
                     Ä # And take the absolute value of this result
                       # (after which it is output implicitly)

```
> 1 votes

# Answer
# APL (Dyalog Classic), 37 bytes

```
{(a b n k)←⍵⋄l←n÷⍨b-a⋄l×+/⍺⍺a+l×k+⍳n}

```

Try it online!

# APL NARS, 37 chars

The function has the argument in the left the function, in the right numeric argument a b n k. In the question k=left here it means k=¯1; k=right here it means k=0. Test:

```
  f←{(a b n k)←⍵⋄l←n÷⍨b-a⋄l×+/⍺⍺a+l×k+⍳n}
  {1+2×⍵} f 5 13 4 0
168
  {√⍵} f 1 2.5 3 ¯1
1.819479217
  {4+(¯3×⍵)+0.2×⍵×⍵} f 12.5 2.5 10 0
55.5
  {9+(¯4×⍵)+7÷⍨2×⍵×⍵} f 0 15 3 ¯1
13.57142857
  {6-0×⍵} f 1 4 2 0
18
  {1+(165×⍵)+⍵*7} f 7 7 4 ¯1
0
  {⍵×1○÷⍵} f 0 1 50 0
0.3857239529

```
> 0 votes

---
Tags: code-golf, math, function, calculus
---


# Question
Title: Shortest POSIX command line that eagerly removes dual newline sequences
Remove every pair of newline characters, that means every two newline characters appearing together are elided, whereas unaccompanied newline characters remain present. Example:

```
echo -ne 'a\n\nb\nc\n\n\n\nd\n\n\n' | your-command

```

should output the same as

```
echo -ne 'ab\ncd\n'

```

Watch out, some POSIX tools have implementations that diverge from the standard. Please consult https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html before submitting your solution.

# Answer
> 2 votes
# Sed, 22

```
sed ':l;s/\n\n//;N;bl'

```

Try it online!

Initially I had hoped to do `sed -z 's/\n\n//g'` for a score of 18, but I think `-z` is a GNU extension and not Posix.

# Answer
> 1 votes
# Bash, 32 bytes

```
awk 'BEGIN{RS="\n\n";ORS="";} 1'

```

Try it online!

# Answer
> 1 votes
## AWK, ~~26~~ 22 bytes

```
awk -vRS='

' -vORS= 1

```

Tested with `gawk` and `mawk` on MacOS.

Edit: saved 4 bytes thanks to @AndersKaseorg.

---
Tags: code-golf, string
---


title: Score a game of Bowling

text:
# Question
Title: Score a game of Bowling
Your task is to sum up and output one player's score in a game of 10-pin bowling after *up to* 21 **rolls**.

The rolls are represented as a sequence of integers in your preferred method of input. Each integer corresponds to the number of pins that were knocked down in that roll.

## Scoring

After each **round** the number of pins knocked down in that round is counted into the final score. If a player knocks down all ten pins in the first roll of a round, this is a **strike**, and the round is over. Otherwise, the round lasts for one more roll. If the second roll of a round knocks down all the remaining pins, this is a **spare**.

For each strike there is a **bonus** equal to the sum of pins knocked down in the two next rolls. For each spare there is a bonus equal to the number of pins knocked down in the next roll.

The 10th and final round, the player may be granted extra rolls: In case of a strike, the player gets two more rolls to make up his strike bonus. In case of a spare, the player gets one more roll.

## Examples

```
Input: 4 3 8 2 7 1 10 7 3 0 10 2 2 10 10 5 4
Output: 131

Input: 10 10 9 1 7 3 2 7 10 1 9 10 7 1 10 10 10
Output: 183

```

## Rules

* You may assumed that the input is valid.
* As per Mego's comment I have loosened the requirements for the input/output methods to meet our current standard.
* Answers in **languages that are newer than the challenge are allowed**
* Shortest code wins!

# Answer
> 6 votes
### GolfScript, 50 41 characters

```
~0]-1%~0{\.9>{+1$3$}{@+.9>3$*}if++}10*p];

```

Another attempt in GolfScript (run it online).

An explanation of the code follows. The solution utilises the stack nature of the problem (consume rolls one after another) but therefore the input has to be reversed.

```
~0          # Take the input and evaluate to single numbers on the stack. Add zero.
]-1%~       # Reverse the stack (make array, reverse array, dump array)

0           # Start with a sum of zero
{           # Perform this block 10 times (once for each round)
  \         #   Take the next roll
  .9>{      #   If it is a strike
    +       #     Add the value of the roll to the sum
    1$3$    #     and duplicate top two members of the stack (i.e. next two rolls).
  }{        #   ... else ...
    @+      #     Take the next roll and add with first roll in round.
    .9>     #     Does this sum show a spare?
    3$*     #     Get next roll (potential bonus) and multiply with yes/no.
            #     Since we pushed an additional 0 in the beginning
            #     there is a spare roll even for the last round.
  }if       #   endif
  ++        #   Add top three stack entries together
            #   (i.e. sum+2 bonus rolls for strike, sum+rolls+bonus else)
}10*        # Loop ten times

p];         # Sum is top of stack. Print sum and discard any leftover rolls.

```

Previous version:

```
~].1>.1>]zip{((.10<{@(0=@+@1>1$9><}*@}10*;]{+}.@**

```

# Answer
> 5 votes
## Python, 116 110 105 103 100 99 characters

```
z=map(int,raw_input().split())
s=0
exec('s+=sum(z[:2+(z[0]+z[1]>9)]);z=z[2-(z[0]>9):];'*10)

```

Spending 30 characters on input is irksome. Suggestions welcome.

Much thanks to Howard for improvements.

# Answer
> 4 votes
# R, 101 bytes

I am not sure why this challenge was bumped, but I like it, so I'll late answer anyways.

```
f=function(x,s=0,c=10)`if`(c&length(x),f(x[-(0:(x[1]!=10)+1)],sum(x[1:(2+(sum(x[1:2])>9))])+s,c-1),s)

```

Try it online!

Ungolfed:

```
f <- function(throws, score = 0, count = 10){
  if(count != 0 & length(throws) != 0){
    IsStrike <- throws[1] == 10
    IsStrikeOrSpare <- sum(throws[1:2]) >= 10
    f(throws[-c(1, 2 * !IsStrike)],
      score + sum(throws[c(1:(2 + IsStrikeOrSpare))]),
      count - 1)
  } else {
    return(score)
  }
}

```

Recursive function. Takes `x` as input, which holds the scores. Initialises the `s`cores and `c`ounts the amount of rounds thrown.

The if statement checks if 10 rounds are thrown, or if `x` is empty. If that is the case, the score is returned. Else the function will call itself as follows:

It removes the throws from `x`, by checking if it is a strike or not. If so, the first entry is removed, else the first two. `(S=x[1]!=10)` checks for strikes. We remove (`-`) index `0:S`, where `S` is 1 if it is a strike, and 0 if not. And then we add one: `-(0:(x[1]!=10)+1)`. We pass the shortened `x` to the next call.

As for the score, this is found by taking `x[1:2]` if it is a regular turn, and `x[1:3]` if it is a strike or a spare. We check if `sum(x[1:2])` is bigger or equal than 10. If it is a strike, obviously this is the case. If it is a spare, then this works as well. So if this is TRUE, we add `x[3]` to the sum. This is then added to `s`.

# Answer
> 1 votes
## CoffeeScript (234 215 170)

```
z=(a)->b=(Number i for i in a.split(' ').reverse());t=0;(r=b.pop();l=b.length;if(9<r)then(t+=r;t+=b[l-1]+b[l-2];)else(f=r+b.pop();t+=f;(t+=b[l-2])if 9<f))for i in[0..9];t

```

**EDIT**: A hefty re-write, shamelessly plagiarising Howard's great stack-based approach. I'm confident more can be stripped out for accessing the last element of an array without destroying it...

# Answer
> 1 votes
# Ruby, 252 bytes

Accepts input into an array add all elements first, then searches for spare and strike bonus

```
s,p,t,r=0,0,1,1
o=ARGV
o.each_with_index do |m,n|
y=m.to_i
s+=y
if r<10
p+=y
if p==10&&t==1
r,p=(r+1),0
s+=o[n+1].to_i+o[n+2].to_i
elsif p<10&&t==1
t=2
elsif p<10&&t==2
t,p,r=1,0,(r+1)
elsif p==10&&t==2
t,p,r=1,0,(r+1)
s+=o[n+1].to_i
end end end
puts s

```

# Answer
> 1 votes
# PHP, 82 bytes

```
for($a=$argv;$r++<10;$i+=$p<10)$s+=(9<$q=$a[++$i+1]+$p=$a[$i])*$a[$i+2]+$q;echo$s;

```

takes input from command line arguments; run with `-nr` or test it online.

**breakdown**

```
for($a=$argv;       # import arguments
    $r++<10;        # loop through rounds
    $i+=$p<10)          # 6. if no strike, increment throw count again
    $s+=(9<
        $q=$a[++$i+1]+  # 1. increment throw count  2. $q=second throw plus
        $p=$a[$i]       # 3. $p=first throw
        )*$a[$i+2]      # 4. if $q>9 (strike or spare), add third throw to sum
    +$q;                # 5. add first and second throw to sum
echo$s;             # print sum

```

# Answer
> 1 votes
# Perl 5, 65 + 2 = 67 bytes

Requires `-ap` flags

```
$\+=(($"=shift@F)<10?$"+=shift@F:10+$F[1])+$F[0]*(9<$")for 0..9}{

```

Try it online!

# Answer
> 1 votes
# Jelly,  ~~36~~  35 bytes

```
+\µi©⁵+Ị$ḂḤị;®×Ị¤¡-
;0Ç3ƤFṣ-m€2Fḣ⁵S

```

A monadic link accepting a list of integers and returning an integer.

**Try it online!**

### How?

Calculates the score of each overlapping run of three bowls as if it were one that started at the beginning of a frame and optionally appends a strike identifier (`-1`), flattens this resulting list, splits it at the strike identifiers, then discards every second result from each chunk (removing the scores of those runs that did not really start with the start of a frame).

To cater for the final frame a zero is first appended to the input (to allow the 3-wise slicing to allow a frame to start on what was the penultimate bowl) and the resulting scores are truncated to the first ten (to remove the now possible bogus 11th frame) prior to summing them up.

```
+\µi©⁵+Ị$ḂḤị;®×Ị¤¡- - Link 1, threeBowlEvaluate: list, bowlScores
                    -               e.g. [0,4,6]   [9,1,10]   [0,4,4]  [10,7,9]
 \                  - cumulative reduce with:
+                   -   addition         [0,4,10]  [9,10,20]  [0,4,8]  [10,17,26]
  µ                 - monadic chain separation, call that "left"
     ⁵              - literal ten        10        10         10       10
   i                - first index in left 3         2 (spare)  0        1 (strike)
    ©               - (copy to register for later reuse)
        $           - last two links as a monad (f(x)):
       Ị            -   abs(x) <= 1       0         0          1        1
      +             -   add x             3         2          1        2
         Ḃ          - modulo by 2         1         0          1        0
          Ḥ         - double              2         0          2        0
           ị        - index into left (both 1-indexed and modular)
                    -            ...      4        20          4       26
                  - - literal -1         -1        -1         -1       -1
                 ¡  - repeat:
            ;       - ...action: concatenate
                ¤   - ...number of times: nilad followed by link(s) as a nilad:
             ®      -   z from register   3         2          0        1
               Ị    -   abs(z) <= 1       0         0          1        1
              ×     -   multiply          0         0          0        1 (strike)
                    - ...yielding:        4         20         4        [26,-1]

;0Ç3ƤFṣ-m€2Fḣ⁵S - Main link: list bowlValues
                -                    e.g. [4,3,8,2,7,1,10,7,3,0,10,2,2,10,10,5,4]
 0              - literal zero            0
;               - concatenate             [4,3,8,2,7,1,10,7,3,0,10,2,2,10,10,5,4,0]
   3Ƥ           - for infixes of length 3:
  Ç             -   last link (1) as a monad
                -                         [7,11,17,9,8,11,[20,-1],10,3,12,[14,-1],4,12,[25,-1],[19,-1],9]
     F          - flatten                 [7,11,17,9,8,11,20,-1,10,3,12,14,-1,4,12,25,-1,19,-1,9]
       -        - literal -1              -1
      ṣ         - split at                [[7,11,17,9,8,11,20],[10,3,12,14],[4,12,25],[19],[9]]
          2     - literal two             2
        m€      - modulo slice for €ach   [[7,17,8,20],[10,12],[4,25],[19],[9]]
           F    - flatten                 [7,17,8,20,10,12,4,25,19,9]
             ⁵  - literal ten             10
            ḣ   - head to index           [7,17,8,20,10,12,4,25,19,9] (no effect this time)
              S - sum                     131

```

# Answer
> 1 votes
# JavaScript (ES6),  ~~79 78 72 69~~  68 bytes

```
f=([x,y,...r],n=9)=>x+y+~~r[!n|x+y>9?0:f]+(n&&f(x>9?[y,...r]:r,n-1))

```

Try it online!

### Commented

```
f = (               // f is a recursive function taking:
  [x,               //   x = result of the current roll
      y,            //   y = result of the next roll
         ...r],     //   r[] = remaining results
  n = 9             //   n = remaining number of rounds
) =>                //
  x + y +           // add x + y to the score
  ~~r[              //
    !n |            // if this is the last round
    x + y > 9 ?     // or this is either a spare or a strike:
      0             //   add the result of the next roll to the score
    :               // else:
      f             //   use a dummy index so that nothing is added
  ] + (             //
    n &&            // if n is not equal to 0:
      f(            //   add the result of a recursive call:
        x > 9 ?     //     if this is a strike:
          [y, ...r] //       re-insert y into r[]
        :           //     else:
          r,        //       pass r[] unchanged
        n - 1       //     decrement n
      )             //   end of recursive call
  )                 //

```

# Answer
> 0 votes
## Perl, 140?

First attempt:

```
#!/usr/bin/perl
# usage: ./bowling.pl [list of scores]

@A=@ARGV;{last if(9<$n++);$a=shift@A;$S+=$a;($S+=$A[0]+$A[1])&redo if($a==10);$b=shift@A;$S+=$b;($S+=$A[0])&redo if(10==$a+$b);redo}print$S

```

Sadly, there are certain cases where it fails. I will come and redo it later.

---
Tags: code-golf, number, game
---


title: Give me Triangles

text:
# Question
Title: Give me Triangles
Given an integer `n>0`, write a program that will output an "isosceles" Triangle out of #'s of height `n`.

Examples:

`n=3`

```
  #
 ###
#####

```

`n=1`

```
#

```

`n=5`

```
    #
   ###
  #####
 #######
#########

```

This would be invalid:

```
#
###
#####
#######
#########

```

# Answer
> 9 votes
# Charcoal, 5 bytes

```
Ｇ↗↘Ｎ#

```

Try it online! Link is to verbose version of code. Explanation: The  draws a filled polygon, where the `↗↘` specifies the sides to follow (the polygon is automatically closed) and the  inputs the size and the `#` specifies the fill character. Using `Ｇ↖↙Ｎ#` also works of course.

Alternate solution, also 5 bytes:

```
Ｇ^Ｎ#⟲

```

Try it online! Link is to verbose version of code. Explanation: The `^` is a shortcut for two diagonal directions `↘↙` (sadly there is no shortcut for the above diagonals in the required order as `<` is `↘↗` and `>` is `↙↖`) so the triangle has to be rotated into position using .

# Answer
> 5 votes
# PowerShell, 36 bytes

```
"$args"..1|%{" "*--$_+"#"*++$i;$i++}

```

Try it online!

Loops from input `$args` down to `1`, each iteration constructing a string consisting of the appropriate number of spaces plus a number of `#` marks that starts at `1` and increments by 2 every iteration. Those strings are left on the pipeline, and implicit output gives us newlines for free.

# Answer
> 4 votes
# C (gcc), ~~104~~ \\$\cdots\\$ ~~72~~ 71 bytes

Saved ~~5~~ 11 bytes thanks to S.S.Anne!!!
Saved 6 bytes thanks to gastropner!!!
Saved a byte thanks to Stephen!!!

```
i;j;f(n){for(i=0;i++<n;)for(j=0;j<i*2;)printf(j++?"#":"\n%*s",n-i,"");}

```

Try it online!

# Answer
> 4 votes
# Python 2, 46 bytes

```
def f(n,i=1):1/n;print" "*~-n+"#"*i;f(n-1,i+2)

```

Try it online!

Basically the same solution as Jonathan Allan, but a function that prints and terminates with error, if that's allowed here. The `1/n` is used to halt execution where `n=0`. Maybe there's a way to do that shorter by stuffing in a `/n` or `%n` somewhere.

# Answer
> 4 votes
# 05AB1E, 8 bytes

Multiple 8 bytes programs are possible:

**Explanations:**

```
·         # Double the (implicit) input-integer
          #  i.e. 3 → 6
 ÅÉ       # Pop and push a list of all positive odd values below this doubled value
          #  → [1,3,5]
   '#×   '# Repeat "#" that many times as string
          #  → ["#","###","#####"]
      .c  # Centralize this list (which implicitly joins by newlines)
          #  → "  #\n ###\n#####"

L         # Push a list in the range [1, (implicit) input-integer]
          #  i.e. 3 → [1,2,3]
 '#×     '# Repeat "#" that many times as list
          #  → ["#","##","###"]
    €û    # Palindromize each
          #  → ["#","###","#####"]
      .c  # Centralize this list (which implicitly joins by newlines)
          #  → "  #\n ###\n#####"

L         # Push a list in the range [1, (implicit) input-integer]
          #  i.e. 3 → [1,2,3]
 ·        # Double each value
          #  → [2,4,6]
  <       # Decrease each by 1
          #  → [1,3,5]
   '#×.c '# Same as the first answer above

'#×      '# Repeat "#" the (implicit) input-integer amount of times as string
          #  i.e. 3 → "###"
   η      # Take the prefixes of that string
          #  → ["#","##","###"]
    j     # Pad spaces to each to make the total length equal to the (implicit) input
          #  i.e. 3 → ["  #"," ##","###"]
     €û   # Palindromize each
          #  → ["  #  "," ### ","#####"]
       »  # Join by newlines
          #  → "  #  \n ### \n#####"

```

For each of these programs the resulting string is then output implicitly (with trailing newline).

# Answer
> 3 votes
# Ruby, ~~46~~ 43 bytes

```
f=->g{g.times{|n|puts" "*(g-n)+?#*(2*n+1)}}

```

Try it online!

* -3 thanks to IMP1

# Answer
> 3 votes
# , ~~19~~ 18 bytes

```
' #'(#~|.,.1++:)i.

```

Try it online!

*-1 byte thanks to FrownyFrog*

Let's do 3:

* `i.` Produces:

```
0 1 2

```
* `|.,.1++:` \- Reverse `|.` produces `2 1 0` and `1 +` the double `+:` produces `1 3 5`. Then we zip `,.` those together:

```
2 1
1 3
0 5

```
* `' #'#~` copies each character in the 2-character string `#` (space and pound) according to the mask specified above, and pads the end of the first two rows with spaces, so every row is 5 characters:

```
  #
 ###
#####

```

# Answer
> 2 votes
# cQuents, 18 bytes

```
|
&@ (n-$)~@#(2$-1

```

Try it online!

## Explanation

```
|
                   terms in sequence are separated by newline
&                  output first n terms in sequence
                   each term is:
 @                 " " *
   (n-$)                 n - index
        ~                          concat
         @#                               "#" *
           (2$-1                                2 * index - 1

```

# Answer
> 2 votes
# APL+WIN, 23 bytes

Prompts for integer:

```
(-⌽⍳n)⌽⊃(1+2×⍳n←⎕)⍴¨'#'

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 2 votes
# MATL, 11 bytes

```
:&<~P2&ZvZc

```

**Try it online!**

### How it works

Consider input `3` as an example.

```
:      % Implicit input. Range
       % STACK: [1 2 3]
&<     % Pairwise less-than comparison
       % STACK: [0 0 0;
                 1 0 0
                 1 1 0]
~      % Negate, elementwise
       % STACK: [1 1 1;
                 0 1 1;
                 0 0 1]
P      % Flip vertically
       % STACK: [0 0 1;
                 0 1 1;
                 1 1 1]
2&Zv   % Reflect horizontally, without repeating last column
       % STACK: [0 0 1 0 0;
                 0 1 1 1 0;
                 1 1 1 1 1]
Zc     % Replace nonzeros by '#' and zeros by ' '
       % STACK: ['  #  '
                 ' ### ';
                 '#####']
       % Implicit display

```

# Answer
> 2 votes
# Python 2, 48 bytes

```
n=input();v=1
while n:n-=1;print' '*n+'#'*v;v+=2

```

**Try it online!**

---

A fun **49** with an extra space of padding is:

```
s=' '*input()+'#'
while'#'>s:print s;s=s[1:]+'##'

```

Try that

# Answer
> 2 votes
# Red, ~~78~~ 76 bytes

```
func[n][s: copy"#"repeat i n[print pad/left s n + i - 1 append s"##"take s]]

```

Try it online!

## Alternative using Red's `parse`:

# Red, 77 bytes

```
func[n][s: to""pad/left"#"n loop n[parse s[(print s take s)to"#"insert"##"]]]

```

Try it online!

# Answer
> 2 votes
# k4 23 bytes

-6 thanks to streetster!

```
{(-x+!x)$(1+2*!x)#'"#"}

```

29 bytes previous solution+explanation:

```
{(-x+!x)$|:'x#x("##",)\"# "}

{                          } /lambda with implicit arg `x`
              x("##",)\"# "  /function composition - cumulatively join (,) "##" to "# " x times and return intermediate results ("# ";"### ";"##### ") etc
            x#               /take x items
         |:'                 /reverse each
 (-x+!x)                     /enumerate x and subtract x from each (x=3 -> -3+0 1 2)
        $                    /pad, left-pads when left arg is negative

```

# Answer
> 2 votes
# Rule 222, 1 byte (noncompeting)

```
#

```

Wolfram codes describe a family of celular automata. While most behave in very simple ways, some of them show very complex behaviour. Rule 110 is even Turing complete.

Rule 222 is one of the "simple" ones. After n generations, it produces a triangle of n levels, as specified in the challenge. A synonymous cellular automata in this case is Rule 254.

# Answer
> 1 votes
# Jelly, 11 bytes

```
>þ`UŒBị⁾ #Y

```

Try it online!

A full program that takes an integer argument and prints a triangle. If a monadic link returning a list of Jelly strings is acceptable, the final byte can be saved for 10 bytes.

## Explanation

```
>þ`         | Outer table using greater than and 1..n as both left and right argument
   U        | Reverse order of inner lists
    ŒB      | Bounce inner lists (i.e. repeat each one in reversed order without duplicating the final character)
      ị⁾ #  | Index into [" ", "#"]
          Y | Join with newlines

```

# Answer
> 1 votes
# Python 3, 58 bytes

```
def f(n,i=1):print((n-i)*' '+(2*i-1)*'#');n>i and f(n,i+1)

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~75~~ 70 bytes

```
i,m;f(n){m=n*2;for(i=m*n;i--;)putchar(i%m?abs(i%m-n)<n-i/m?35:32:10);}

```

Try it online!

# Answer
> 1 votes
# Burlesque, 30 bytes

```
2|*J' j|*iSj'#j|*iT2enq\[Z[unQ

```

Try it online!

Not left aligned, but functionally an isosceles triangle. Takes input as `N`.

```
2|*    # N*2
J      # Duplicate this number
' j|*  # 2N spaces
iS     # [2N..1] spaces as list
j      # Swap back
'#j|*  # 2N hashes
iT     # [1..2N] hashes as list
2en    # Take each odd
q\[Z[  # Zip together, and concatenate
un     # Add new lines between each element
Q      # Pretty print

```

# Answer
> 1 votes
# Haskell, ~~91~~ ~~72~~ 62 bytes

```
(1!)
_!0=""
i!n=r n ' '++r i '#'++'\n':(i+2)!(n-1)
r=replicate

```

*-10 bytes* thanks to @Laikoni.

You can try it online!

# Answer
> 1 votes
# Python 2, 54 bytes

```
n,i=input(),1
exec"print(n-i)*' '+(2*i-1)*'#';i+=1;"*n

```

Try it online!

Based on Jitse's Python 3 solution.

# Answer
> 1 votes
# Japt `-R`, 9 bytes

```
õî'# mê û

```

Try it

Or 7 bytes if we can choose which character to use.

```
õ_î¬êÃû

```

Try it

# Answer
> 1 votes
# Haskell, 57 bytes

```
r=replicate
f x=unlines[r(x-n)' '++r(2*n-1)'#'|n<-[1..x]]

```

Try it online!

The `unlines` function is often helpful for ASCII art problems.

# Answer
> 1 votes
# Japt `-R`, 9 bytes

```
ÇÑÄ ç'#
û

```

Try it

# Answer
> 1 votes
# MathGolf, ~~18~~ 17 bytes

```
╒_'#*mñ\x *^my ═n

```

Try it online.

**Explanation:**

```
╒                  # Push a list in the range [1, (implicit) input-integer]
                   #  3 → [1,2,3]
 _                 # Duplicate this list on the stack
  '#*             '# Repeat "#" the values amount of time as string
                   #  → ["#","##","###"]
     mñ            # Palindromize each
                   #  → ["#","###","#####"]
       \           # Swap to get the duplicated [1, input] list at the top again
        x          # Reverse this to [input, 1]
                   #  → [3,2,1]
          *        # Repeat a space the values amount of time as string
                   #  → ["   ","  "," "]
           ^       # Zip the two lists together
                   #  → [["#","   "],["###","  "],["#####"," "]]
            my     # Join each inner pair together
                   #  → ["#   ","###  ","##### "]
               ═   # Pad leading spaces to each string to make them all of equal length
                   #  → ["  #   "," ###  ","##### "]
                n  # And join this list by newlines
                   #  → "  #   \n ###  \n##### "
                   # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# PHP, ~~65~~ ~~64~~ 62 bytes

```
for($j=$argn+$i=1;--$j;$i+=2)printf("%{$j}s%'#{$i}s\n",'','');

```

Try it online!

Muuuuch better version with string formatting. I knew there was something, PHP is a templating language after all.. It couldn't be that bad for this kind of job!!

EDIT: saved 1 byte and removed the extra leading space by moving `$i++` to the `printf`

EDIT2: saved 2 bytes with new strategy by @GuillermoPhillips (thanks!)

**ORIGINAL NAIVE ANSWER:**

# PHP, 104 bytes

```
for($t='#';$i++<$argn;$s.=' ',$t="#$t#"){$r[$i*2]="$t\n";$r[($argn-$i)*2+1]=$s;}ksort($r);echo join($r);

```

Try it online!

# Answer
> 1 votes
# Canvas, 6 bytes

```
｛#×］±│

```

Try it online.

**Explanation:**

```
｛        # Map over the range [1, input]:
  #×      #  Repeat "#" the value amount of times
    ］±   # After the map: interpret the array as a 2D string, and reverse it
       │  # And palindromize it horizontally with 1 overlap
          # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# Java 8, ~~151~~ 128 bytes

`p->{for(int c=1;p>0;c+=2)System.out.println(new String(new char[p--]).replace('\0',' ')+new String(new char[c]).replace('\0','#'));}`

TIO

See also JDK 13 answer

# Answer
> 1 votes
# Icon, 73 bytes

```
procedure f(n,i)
/i&i:=1
write(right(repl("#",i),n+i))
n>1&f(n-1,i+2)
end

```

Try it online!

# Answer
> 1 votes
# Stax, 9 bytes

```
é─C:UÅ≤┘.

```

My first Stax answer. :)

Try it online or try it online unpacked (**10 bytes**).

**Explanation (of the unpacked version):**

```
'#*        '# Repeat "#" the (implicit) input-integer amount of times as string
            #  i.e. 3 → "###"
   |[       # Get the prefixes of this string
            #  → ["#","##","###]
     |>     # Padding leading spaces up to a length equal to the longest string
            #  → ["  #"," ##","###"]
       m    # Map over each line:
        |p  #  Palindromize the line
            #   → ["  #  "," ### ","#####"]
       m    # And the map also prints each line with trailing newline afterwards
            #  → "  #  \n"
            #    " ### \n"
            #    "#####\n"

```

# Answer
> 1 votes
# Haskell, 52 bytes

```
f x=do n<-[1..x];'\n':([n..x]>>" ")++([2..2*n]>>"#")

```

Try it online!

# Answer
> 0 votes
# JDK 13, ~~94~~ 76 bytes

`p->{for(int c=1;p>0;c+=2)System.out.println(" ".repeat(p--)+"#".repeat(c));}`

TIO

With thanks to Kevin for some suggestions in the comments!

# Answer
> 0 votes
# Retina 0.8.2, 21 bytes

```
.+
$*#
#
¶$.'$* $`#$`

```

Try it online! Link includes test cases. Output includes both leading and trailing newlines (but that helpfully separates the test cases!) Explanation:

```
.+
$*#

```

Convert the input to that many `#`s.

```
#
¶$.'$* $`#$`

```

For each `#`, output a new line, then as many spaces as there are `#`s remaining, then the `#`s so far, mirrored.

# Answer
> 0 votes
# JavaScript V8, 48 bytes

```
f=(i,s=`#
`)=>i?(' '.repeat(--i)+s)+f(i,'##'+s):''

```

Test cases:

```
f=(i,s=`#
`)=>i?' '.repeat(--i)+s+f(i,'##'+s):''

console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
console.log(f(5))
console.log(f(6))
```

# Answer
> 0 votes
# Ruby, 42 bytes

Copying the Python answer from xnor.

```
f=->n,i=1{1/n;puts" "*~-n+?#*i;f[n-1,i+2]}

```

Try it online!

---
Tags: code-golf, ascii-art
---


# Question
Title: Estimate the mean minimum Hamming distance
**Task**

Inputs \\$b \leq 100\\$ and \\$n \geq 2\\$. Consider \\$n\\$ binary strings, each of length \\$b\\$ sampled uniformly and independently. We would like to compute the expected minimum Hamming distance between any pair. If \\$n = 2\\$ the answer is always \\$b/2\\$.

**Correctness**

Your code should ideally be within \\$\pm0.5\\$ of the correct mean. However, as I don't know what the correct mean is, for values of \\$n\\$ which are not too large I have computed an estimate and your code should be within \\$\pm0.5\\$ of my estimate (I believe my estimate is within \\$\pm0.1\\$ of the correct mean). For larger values than my independent tests will allow, your answer should explain why it is correct.

* \\$b = 99, n = 2^{16}.\\$ Estimated avg. \\$19.61\\$.
* \\$b = 89, n = 2^{16}.\\$ Estimated avg. \\$16.3\\$.
* \\$b = 79, n = 2^{16}.\\$ Estimated avg. \\$13.09\\$.
* \\$b = 69, n = 2^{16}.\\$ Estimated avg. \\$10.03\\$.
* \\$b = 59, n = 2^{16}.\\$ Estimated avg. \\$7.03\\$.
* \\$b = 99, n = 2^{15}.\\$ Estimated avg. \\$20.67\\$.
* \\$b = 89, n = 2^{15}.\\$ Estimated avg. \\$17.26\\$.
* \\$b = 79, n = 2^{15}.\\$ Estimated avg. \\$13.99\\$.
* \\$b = 69, n = 2^{15}.\\$ Estimated avg. \\$10.73\\$.
* \\$b = 59, n = 2^{15}.\\$ Estimated avg. \\$7.74\\$.
* \\$b = 99, n = 2^{14}.\\$ Estimated avg. \\$21.65\\$.
* \\$b = 89, n = 2^{14}.\\$ Estimated avg. \\$18.23\\$.
* \\$b = 79, n = 2^{14}.\\$ Estimated avg. \\$14.83\\$.
* \\$b = 69, n = 2^{14}.\\$ Estimated avg. \\$11.57\\$.
* \\$b = 59, n = 2^{14}.\\$ Estimated avg. \\$8.46\\$.

**Score**

Your base score will be the number of the examples above that your code gets right within \\$\pm0.5\\$. On top of this you should add \\$x \> 16\\$ for the largest \\$n = 2^x\\$ for which your code gives the right answer within \\$\pm0.5\\$ for all of \\$b = 59, 69, 79, 89, 99\\$ (and also all smaller values of \\$x\\$). That is, if your code can achieve this for \\$n=2^{18}\\$ then you should add \\$18\\$ to your score. You only get this extra score if you can also solve all the instances for all smaller \\$n\\$ as well. The number of strings \\$n\\$ will always be a power of two.

**Time limits**

For a single \\$n, b\\$ pair, your code should run on TIO without timing out.

**Rougher approximation answers for larger values of \\$n\\$**

For larger values of \\$n\\$ my independent estimates will not be as accurate but may serve as a helpful guide nonetheless. I will add them here as I can compute them.

* \\$b = 99, n = 2^{17}.\\$ Rough estimate \\$18.7\\$.
* \\$b = 99, n = 2^{18}.\\$ Rough estimate \\$17.9\\$.
* \\$b = 99, n = 2^{19}.\\$ Rough estimate \\$16.8\\$.

# Answer
# Python 3, score = big(?)

```
from math import exp, log, log1p

def f(b, n):
    e = n * (n - 1) / 2
    m = 0
    c = 1
    s = 0
    t = 1 << b
    for k in range(b):
        s += c
        m += exp(e * (log1p(-s / t) if 2 * s < t else log((t - s) / t)))
        c = c * (b - k) // (k + 1)
    return m

```

Try it online!

The Hamming distance \\$D\_{x, y}\\$ between any two of the strings (\\$1 \le x \< y \le n\\$) is a random variable distributed as the Binomial distribution \\$B{\left(b, \tfrac12\right)}\\$:

$$ \Pr\[D\_{x, y} \> k\] = 1 - \frac{1}{2^b} \sum\_{i=0}^k \binom bi. $$

Furthermore, any (distinct) *two* of these \\$\binom n2\\$ random variables are independent.

If we make the incorrect but empirically useful assumption that *all* \\$\binom n2\\$ of these random variables are independent, then we can compute the distribution of their minimum \\$D = \min\_{1 \le x \< y \le n} D\_{x,y}\\$ exactly:

$$ \begin{gather\*} \Pr\[D \> k\] = \left(1 - \frac{1}{2^b} \sum\_{i=0}^k \binom bi\right)^{\binom n2}, \\ \mathbb E\[D\] = \sum\_{k=0}^{b-1} \Pr\[D \> k\]. \end{gather\*} $$

This result can be computed extremely quickly and seems to be close enough. Numerical evidence suggests that the absolute error is worst at \\$b = 1, n = 3\\$ (where we estimate the expected minimum as \\$\tfrac18\\$ when it is actually \\$0\\$), and drops off quickly to zero as \\$b\\$ and/or \\$n\\$ get large.
> 11 votes

---
Tags: math, code-challenge, combinatorics, probability-theory
---


title: Is this number a hill number?

text:
# Question
Title: Is this number a hill number?
A hill number is a number that has **the same digit in the first & the last**, but that's not all. In a hill number the first digits are **strictly increasing** until the largest digit, and after the largest digit, the last digits are **strictly decreasing. The largest digit can be repeated but consecutively only**, meaning no gaps by smaller numbers.

Here is an example of a hill number:

```
12377731 | 1237...             | ...731
^ same ^ | strictly increasing | strictly decreasing
---------+---------------------+---------------------
12377731
   ^^^ okay because largest digit can be repeated

```

This is **not**:

```
4588774 | ...8774
        |     ^^ not the largest digit
        |        so this has to be strictly decreasing
        |        but it's not, so not a hill number

```

### Challenge

Given a positive integer, write a full program or a function that returns truthy for hill numbers but falsy on other values.

**Notes:**

* Input & output can be in **any reasonable format**.
* This is so shortest answer in each language wins!

### Test Cases

```
12321 -> Truthy
1233321 -> Truthy
99 -> Truthy
3 -> Truthy
234567992 -> Truthy
5555555 -> Truthy
1232 -> Falsy
778896 -> Falsy
23232 -> Falsy
45566554 -> Falsy
5645 -> Falsy

```

# Answer
# Jelly, 8 bytes

```
_ƝṠÞ+SƊƑ

```

Try it online!

### How it works

```
_ƝṠÞ+SƊƑ  Main link. Argument: n (integer)

_Ɲ        Take the differences of neighboring digits.
          This maps n = abcd to [a-b, b-c, c-d].
       Ƒ  Fixed; apply the link to the left and return 1 if the result is equal to
          its argument, 0 if not.
      Ɗ       Drei; combine the three links to the left into a monadic chain.
  ṠÞ              Sort the differences by their signs (negative, zero, positive).
     S            Take the sum of the differences, yielding 0 if and only if the
                  first digit is equal to the last.
    +             Add the sum to each difference.

```
> 10 votes

# Answer
# JavaScript (ES6), ~~62~~ 54 bytes

Takes input as a string. Returns a Boolean value.

```
s=>s[-[...s].some(p=q=n=>q>(q=Math.sign(p-(p=n))))]==p

```

Try it online!

### Commented

```
s =>                  // s = input string
  s[                  // we will eventually access either s[0] or s[-1]
    -[...s].some(     // depending on the result of this some()
      p = q =         // initialize p and q to non-numeric values
      n =>            // for each digit n:
        q > (         //   compare q with
          q =         //   the new value of q,
          Math.sign(  //   defined as the sign of
          p - (p = n) //   the difference between the current digit and the previous one
        ))            //   yield true if the previous q is greater than the new q
    )                 // s[-1] being undefined, a truhty some() will force the test to fail
  ] == p              // otherwise: test if the 1st digit s[0] is equal to the last digit p

```

---

# JavaScript (ES6), 65 bytes

A solution using a regular expression. Takes input as a string. Returns \\$0\\$ or \\$1\\$.

```
s=>/N(,-\d+)*(,0)*[^0-]*$/.test([...s].map(p=v=>p-(p=v)))&p==s[0]

```

Try it online!

### How?

We first convert the number to a list of pairwise digit differences in \\$\[-9,9\]\\$:

```
[...s].map(p = v => p - (p = v))

```

*Example:*

```
"234567992" --> [ NaN, -1, -1, -1, -1, -1, -2, 0, 7 ]

```

This array is coerced to a string, which gives:

```
"NaN,-1,-1,-1,-1,-1,-2,0,7"

```

We apply the following regular expression:

```
 +-----------------------> the second 'N' of 'NaN'
 |    +------------------> a sequence of negative numbers
 |    |     +------------> a sequence of zeros
 |    |     |     +------> a sequence of positive numbers
 |    |     |     |  +---> end of string
 |    |     |     |  |
 |/¨¨¨¨¨¨\/¨¨¨\/¨¨¨¨\|
/N(,-\d+)*(,0)*[^0-]*$/

```

Finally, we also test if the last digit `p` is equal to the first digit `s[0]`.
> 6 votes

# Answer
# Jelly, 11 bytes

```
DIµṠNṢƑaS¬$

```

Explanation:

```
D               Convert to a list of Digits.
 I              Increments; compute differences between successive elements.
  µ             Start new µonadic link.
   Ṡ              Find Ṡign of each increment
    N             then negate;
     ṢƑ           is the result invariant under Ṣorting?
                  If so, the increments consist of some positive numbers,
                     followed by some 0s, followed by some negative numbers,
                     which is what we want.
       a          Logical AND this result with
        S¬$       logical NOT of the Sum of the increments.
                  If the sum of the increments is zero, first and last digits are equal.

```

Try it online!
> 4 votes

# Answer
# Pyth, 16 bytes

```
&SI_._MJ.+jQT!sJ

```

Try the test suite.

```
          jQT          input in base 10
       J.+             J = differences: [3,1,4,1] -> [-2,3,-3]
    ._M                Signs of each element of J
   _                   Reverse the list
 SI                    and check if it is Invariant under Sorting.
                       If this is true, J consists of some positive numbers,
                         followed by some 0s, followed by some negative numbers,
                         which is what we want.
            !sJ        Now we check the other hill condition by ensuring
                         sum(differences) = 0; i.e. the first and last digit are equal.
&                      We take the logical AND of both conditions.

```
> 4 votes

# Answer
# Perl 6, 39 bytes

```
{.[0]==.tail&&[<=] $_ Z<=>.skip}o*.comb

```

Try it online!

### Explanation

```
{ ... }o.comb  # Split into digits and feed into block
.[0]==.tail    # First element equals last
&&             # and
     $_ Z<=>.skip  # Pairwise application of three-way comparator
[<=]           # Results never decrease

```
> 4 votes

# Answer
# Python 2, ~~114~~ 112 bytes

```
lambda n:all((n[0]==n[-1])*sorted(set(x))==list(x)[::d]for x,d in zip(n.split(max(n)*n.count(max(n)),1),[1,-1]))

```

Try it online!
> 3 votes

# Answer
# , 65 bytes

Takes strings. Took the idea for checking sort invariance from the Pyth answer.

```
function(a)!sum(d<-diff(utf8ToInt(a)))&all(sort(k<-sign(d),T)==k)

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~19~~ ~~17~~ ~~13~~ 12 bytes

```
¥D.±Â{RQsO_*

```

-5 bytes by creating a port of *@lirtosiast*'s Pyth answer.

Try it online or verify all test cases.

**Explanation:**

```
¥           # Push the deltas of the digits of the (implicit) input
            #  i.e. 4588774 → [1,3,0,-1,0,-3]
 D          # Duplicate this list
  .±        # Get the sign of each
            #  [1,3,0,-1,0,-3] → [1,1,0,-1,0,-1]
    Â       # Bifurcate (short for DR: Duplicate and Reverse copy)
            #  i.e. [1,1,0,-1,0,-1] → [-1,0,-1,0,1,1]
     {      # Sort the copy
            #  i.e. [-1,0,-1,0,1,1] → [-1,-1,0,0,1,1]
      R     # Reverse it
            #  i.e. [1,1,0,0,-1,-1]
       Q    # And check if they are equal
            #  i.e. [1,1,0,-1,0,-1] and [1,1,0,0,-1,-1] → 0 (falsey)
s           # Swap to get the list of deltas again
 O          # Take the sum
            #  i.e. [1,3,0,-1,0,-3] → 0
  _         # And check if it's exactly 0
            #  0 → 1 (truthy)
*           # Check if both are truthy (and output implicitly)
            #  i.e. 0 and 1 → 0 (falsey)

```

`Â{RQ` can alternatively be `(Â{Q` for the same byte-count, where `(` negates each sign: Try it online.
> 2 votes

# Answer
# J, 23 bytes

```
[:((0=+/)**-:*/:*)2-/\]

```

Idea stolen from the Jelly answers. Just wanted to see how short I could make it in J.

Try it online!
> 2 votes

# Answer
# MATL, 12 bytes

```
dZSd1<AGds~*

```

Try it online!

### Explanation

Input is a string of digits. Output is a `1` or `0`. The number `222222` is a hill number according to this program. Saved 2 bytes by copying Dennis' method for checking equality of the first and last digits.

```
d               % Takes the difference between digits
 ZS             % Calculate the sign.
   d            % Take the difference again.
    1<          % A number is a hill number if these differences are < 1.
      A         % Truthy iff above is all true OR if array is empty (necessary for short inputs)
       Gds      % Push the input, and sum all the differences.
          ~     % Negate
           *    % Multiply the two tests (=logical AND).

```
> 2 votes

# Answer
# Python 2, 53 bytes

```
def f(s):x=map(cmp,s,s[1:]);s[:sorted(x)==x]!=s[-1]>_

```

Takes input as a string. Output is via presence or absence of an exception.

Try it online!

---

# Python 2, 62 bytes

```
lambda s:s[:eval('<='.join(map(str,map(cmp,s,s[1:]))))]==s[-1]

```

Takes input as a string and returns a Boolean.

Try it online!
> 2 votes

# Answer
# Ruby, 47 bytes

```
->n{(r=n.each_cons(2).map{|a,b|a<=>b})==r.sort}

```

Try it online!

Input as array of digits, output is boolean.
> 2 votes

# Answer
# Japt, 11 bytes

Takes input as a digit array.

```
ä-
eUñg)«Ux

```

Try it or run all test cases

```
             :Implicit input of digit array U
ä-           :Deltas
\n           :Reassign to U
 Uñ          :Sort U
   g         :  By signs
e   )        :Check for equality with U
     «       :Logical AND with the negation of
      Ux     :U reduced by addition

```
> 1 votes

# Answer
# Mathematica/Wolfram Language, 69 64 bytes

Pure function. Takes input as an integer, returns `True` or `False`.

```
Sort[x=Sign@-Differences[y=IntegerDigits@#]]==x&&y[[1]]==Last@y&

```

### Explanation:

The first clause checks the "hilliness":

* `IntegerDigits`: Get digits from integer. Store in `y`.
* `-Differences`: Take successive differences and flip signs.
* `Sign`: Replace each entry with +1 if positive, 0 if zero, and -1 if negative. Store in `x`.
* `Sort`: Sort list of +1, 0, -1 from smallest to largest. Compare to original list in `x`.

The second clause checks whether the first and last digits are equal.

A tip of the hat to @IanMiller for tips on refining this code.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 115 bytes

```
s=>!s.Where((c,i)=>i<1?c!=s[^1]:i>s.LastIndexOf(s.Max())?c>=s[i-1]:i>s.IndexOf(s.Max())?s.Max()!=c:c<=s[i-1]).Any()

```

Try it online!

Here is an overview of how this works...

1. Input is in the form of a `string`
2. Find the largest digit
3. Ensure the first and last digits are the same
4. Ensure digits after the last occurrence of the largest digit are decreasing
5. Ensure digits between the first and last occurrence of the largest digit are equal to the largest digit
6. Ensure digits before the first occurrence of the largest digit are increasing
> 1 votes

# Answer
# Burlesque, 22 bytes

```
XXJl_-]==j2COqcm^mso&&

```

Try it online!

```
XX    # Explode into digits
J     # Duplicate
l_-]  # Head & Tail
==    # Are equal
j     # Reorder stack
2CO   # 2-grams
qcm^m # Compare with UFO operator
so    # If sorted
&&    # If going up then down AND head-tail is equal

```
> 1 votes

# Answer
# Retina 0.8.2, 52 bytes

```
.
$*1;$&$*1,
(1+),\1
,
^(1+);(,1+;)*(,;)*(1+,;)*\1,$

```

Try it online! Link includes test cases. Explanation:

```
.
$*1;$&$*1,

```

Convert each digit to unary twice, separated by `;`s and terminated by `,`s. However, you can then think of the result as the first digit, a `;`, then all the pairs of adjacent digits, the digits of each pair separated by `,` and the pairs separated by `;`s, then another `;`, then the last digit, then a final `,`.

```
(1+),\1
,

```

Subtract the pairs of adjacent digits. This leaves `;,;` for equal digits and `1`s on the greater side for unequal digits. (This could be done as part of the following regex but obviously that wouldn't be so golfy.)

```
^(1+);(,1+;)*(,;)*(1+,;)*\1,$

```

Match the first digit, then any number of pairs of ascending digits, then any number of pairs of equal digits, then any number of pairs of descending digits, then match the first digit again at the very end.
> 0 votes

# Answer
# Red, 181 bytes

```
func[n][m: last sort copy t: s: form n
parse t[opt[copy a to m(a: sort unique a)]copy b thru any m
opt[copy c to end(c: sort/reverse unique c)]](s = rejoin[a b c])and(s/1 = last s)]

```

Try it online!

## More readable:

```
f: func[n][
    t: s: form n
    m: last sort copy t
    parse t [ opt [ copy a to m (a: sort unique a) ]
              copy b thru any m
              opt [ copy c to end (c: sort/reverse unique c) ]
            ]
    (s = rejoin [ a b c ]) and (s/1 = last s)
]

```
> 0 votes

# Answer
# Powershell, 77 bytes

```
($x=-join("$($args|%{"-$_;$_"})"|iex))-match'^(-\d)+0*\d+$'-and$x[1]-eq$x[-1]

```

Less golfed test script:

```
$f = {
                                           # $args = 1,2,3,3,3,2,1
$a=$args|%{"-$_;$_"}                       # "-1;1","-2;2","-3;3","-3;3","-3;3","-2;2","-1;1"
$d="$a"                                    # "-1;1 -2;2 -3;3 -3;3 -3;3 -2;2 -1;1"
$x=-join($d|Invoke-Expression)             # "-1-1-100111"
$x-match'^(-\d)+0*\d+$'-and$x[1]-eq$x[-1]  # $true or $false

}

@(
    ,($True , 1,2,3,2,1 )
    ,($True , 1,2,3,3,3,2,1 )
    ,($True , 9,9 )
    ,($True , 3 )
    ,($True , 2,3,4,5,6,7,9,9,2 )
    ,($False, 1,2,3,2 )
    ,($False, 7,7,8,8,9,6 )
    ,($False, 2,3,2,3,2 )
    ,($False, 4,5,5,6,6,5,5,4 )
    ,($False, 5,6,4,5 )
) | % {
    $expected,$a = $_
    $result = &$f @a
    "$($result-eq$expected): $result"
}

```

Output:

```
True: True
True: True
True: True
True: True
True: True
True: False
True: False
True: False
True: False
True: False

```
> 0 votes

# Answer
# Python 3, 114 bytes

```
def f(r):
 l=[*r]
 for i in-1,0:
  while 1<len(l)and l[i]<l[(1,-2)[i]]:l.pop(i)
 return 2>len({*l})and r[0]==r[-1]

```

Try it online!

Way longer than some Python 2 solutions, but this one is def-based and I like it.
> 0 votes

---
Tags: code-golf, decision-problem, number-theory
---