title: Can Gravity Guy Make It?

text:
# Question
Title: Can Gravity Guy Make It?
Gravity Guy is a game where the only user input is a single key that flips the direction of gravity. Given an ASCII art level, determine if it is possible for Gravity Guy to reach the end.

---

## Rules

* The initial direction of gravity is **down**.
* The first column of the input will always contain only *one* `#`, which Gravity Guy **starts on** top of.
* Each iteration, he **moves** to the character directly on his **right**.
* If his **path is blocked** and he moves into a `#`, the player **loses**.
* After moving, the player can **optionally switch gravity** from down to up, or up to down.
* Gravity Guy then **falls on to the next `#`** (in the current direction of gravity).
* If there is no `#` to fall on to and he **falls off the grid**, the player **loses**.
* If Gravity Guy **moves off the right side** of the input grid, the player **wins**.

## Example

If this was the input grid:

```
  ###

#  # #
 ###

```

Gravity Guy would start at the `x` and the be at these positions after each iteration. `^` = switch gravity to up and `v` = switch gravity to down.

```
v                        ^                               v
-------------------------------------------------------------
  ###   |    ###   |    ###   |    ###   |    ###   |    ###
x       |          |    x     |     x    |      x   |
#  #    |  #x #    |  #  #    |  #  #    |  #  #    |  #  # x
 ### #  |   ### #  |   ### #  |   ### #  |   ### #  |   ### #

```

As you can see, by switching gravity at these times Gravity Guy reaches the end, so this input would return a truthy value.

## Specifications

* Input grid can be in any appropriate "grid" format (multiline string padded with spaces, array of line strings, array of array of characters, etc).
* If it is **possible** for the player to win the level, output a `truthy` value. If not, output a `falsey` value.
* The width and height of the grid will be `50` characters at most.
* This is , may the shortest code in bytes win!

## Test Cases

(each case separated by `----------`, any blank lines should also be padded with spaces)

### True

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

----------

###

----------

   #####

####

----------

 #####
 # # #

# # #
 #####

----------

   ############

######      ######

   ############

----------

  ###   ###
     # #
####  #  ####
    #   #
     # #
      #

----------

    ######
   #
 ##
     #######
###     #
   #    #
    #####

----------

    #####
   #    #
 ##     #
     #######
###
   #
    ######

----------

  ###

#  # #
 ###

----------

  ###  ###

###     ##
   #    #
    #####

----------

  #
     #   #
       #
#   #     #
        #
   #
      #
 #

----------

    ##### ####
   #     #    #
  #   # #  ##  #
             #  #
#####  ####   #
               #
     #########

----------

 ###########################
 #   #   #   #     #   #   #
 # # # #   #   # #   #   # #
 # # # ######### ###########
 # # # #  #       #     #  #
   # # # ## ##### ### #
## #   #    #          ## ###
 # ##### #### ###########  #
 # #     #  #     #     ## #
 # # #####  ### # # # # #  #
 #              #   # #   ##
 ###########################

```

### False

```
 ###
   #
####

----------

### ###

----------

    #
 ### ###

#### ###
    #

----------

  ###     ###
     # # #
####  # #  ####
    #     #
     #   #
      # #
       #

----------

  #######
  #     #
 ## #####

### ######
  #     #
  #######

----------

 ###########################
 #   #   #   #  #  #   #   #
 # # # #   #   # #   #   # #
 # # # ######### ###########
 # # # #  #       #     #  #
   # # # ## ##### ### #
## #   #    #          ## ###
 # ##### #### ###########  #
 # #     #  #     #     ## #
 # # #####  ### # # # # #  #
 #              #   # #   ##
 ###########################

```

# Answer
# Snails, 15 bytes

Try it online?

```
^
\ n\ ,=\#r}+~

```

   0. `^` is an option that requires the pattern to start at the top left.

1. `\ `: match space
2. `n`: Turn 90 degrees in either direction
3. `\ ,`: match space zero or more times
4. `=\#` check that there is a `#` in front of us
5. `r`: set the direction to right
6. `}+`: do all of the preceding one or more times
7. `~` match a cell which is out of the grid bounds
> 19 votes

# Answer
# Perl, ~~93~~ ~~89~~ ~~81~~ ~~77~~ ~~76~~ ~~75~~ 74 bytes

Includes +2 for `-0p`

Run with the input pattern (with all lines space padded to the same length) on STDIN:

```
gravity.pl < gravity.txt

```

`gravity.pl`:

```
#!/usr/bin/perl -0p
/
/;$n=".{@-}";s/#$n\K( $n)*\b |(^|w)([w ]$n)*\K $n#/w|$&/es&&redo;$_=m;w

```

This file based version needs the final newline, so that is really 75 bytes. But the commandline based version doesn't need that extra newline so this counts as 74 bytes:

```
perl -0pe '/
/;$n=".{@-}";s/#$n\K( $n)*\b |(^|w)([w ]$n)*\K $n#/w|$&/es&&redo;$_=m;w' < gravity.txt

```

## Explanation:

This will construct a string with a `w` in each positions gravity guy can reach. So for the second to last truthy example it will construct:

```
     #########
    ##### ####
   #wwwww#wwww#
  #w  # #w ##ww#
wwwww wwwwwww#ww#
#####  ####  w#ww
     wwwwwwwwww#
     #########

```

So gravity guy can make it if and only if there is a `w` in the last column. The string will be constructed by replacing one reachable space by `w` in each round.

Each replacement will be of the form

```
s/prefix \K space postfix/ w | $& /e

```

which will demand that the space is preceded by prefix and followed by postfix but replace only the space by `w` without needing lots of advanced grouping.

Assume `$n` contains a regex that will progress just enough that the left and right sides are exactly below each other. Then the relevant regexes are:

```
/^( $n)*\K $n#/       From the first position drop down as long as you
                      encounter spaces until you encounter a #.
                      This puts gravity guy on his starting platform

/#$n\K( $n)*\b /      A space immediately below a # and if you (optionally)
                      go down further from there (as as the descent is
                      over spaces) you get to a space that follows a word
                      boundary. The only way to get a word boundary is if
                      there is a w in front of that space. This selects the
                      position gravity guy ends up on if starting from that
                      w and gravity is up
/w([w ]$n)*\K $n#/    A w followed by a space (or w) and if you go down from
                      there as long as it is over spaces (or w) you finally
                      end up on a space directly above a #. This handles the
                      gravity down case. The test uses "space or w" instead
                      of just space to handle this case:

                       #
                      ww
                      #x
                       #

                      Position x is currently a space and must be replaced by a
                      w but the gravity up regex has already put a w directly
                      after the w gravity guy takes off from. So for gravity
                      down we must handle w as if it is still a space. This
                      is not needed for gravity up because regex always matches
                      starting at the earliest possible character, so
                      gravity up matches before gravity down

```

With that out of the way the program is easy:

```
#!/usr/bin/perl -0p   Slurp all of STDIN into $_, at the end print $_

/\n/                  Match the first newline (needed to measure the row
                      length)
$n=".{@-}"            $n effectively becomes rowlength-1 times ".". This
                      will be the regex that goes one step down a column

s/#$n\K( $n)*\b |(^|w)([w ]$n)*\K $n#/w|$&/es

                     This is the 3 regexes shown above combined. The s
                     modifier is needed so the . in $n also matches newline

    &&redo           Keep looping as long as w's keep getting added

$_=m;w\n;            Check if the last column contains a w: He made it!
                     The \n; at the end is not written. These 2 bytes sneakily
                     come from the -p option for the ; and the -e option
                     for the \n

```
> 9 votes

# Answer
## JavaScript (ES6), 174 bytes

```
a=>[...a[0]].map((_,i)=>[...t].map(x=>s[x]<'#'&&g(s.indexOf('#',x),-1)&&g(s.lastIndexOf('#',x),1),s=a.map(s=>s[i]),t=new Set),t=new Set([0]),g=(i,d)=>i<0||t.add(i+d))&&t.size

```

Takes a horizontal array of strings and returns the number of exit points. Transposing the array costs me 29 bytes. Ungolfed:

```
function gravity(array) {
    var set = new Set;
    set.add(0); // starting point
    for (var i = 0; i < array[0].length; i++) {
        var s = array.map(s => s[i]); // transpose array
        var old = set;
        set = new Set;
        for (var x of old) {
            if (s[x] == '#') continue; // hit wall
            var j = s.indexOf('#', x); // try downward gravity
            if (j >= 0) set.add(j - 1);
            j = s.lastIndexOf('#', x); // try upward gravity
            if (j >= 0) set.add(j + 1);
        }
    }
    return set.size;
}

```
> 3 votes

# Answer
# Pip, ~~85~~ ~~68~~ ~~62~~ 59 + 1 = 60 bytes

Uses the `-r` flag to read all lines of stdin.

```
FcZg{YlFxiIc@xQsyPB(Jc@<x@?`# *$`)+1PB(c@>x@?'#)+x-1i:UQy}i

```

Try it online!

**Brief explanation**

The strategy is essentially a breadth-first search. We transpose the input and loop over the lines (columns), keeping a list of the y-positions the player could reach in that column. The output after the last column is a non-empty list if the player can win, or an empty list (which prints as just a trailing newline) if the player loses.

**Full explanation**

Built-in variables used in this program: `i == 0`, `l == []`, `s == " "`.

The `-r` flag puts a list of the lines of input into `g`. `FcZg{...}` zips `g` and loops over each column `c`. (Unary `Z`, when applied to a list of iterables, acts like Python `zip(*g)`, neatly transposing a 2D array.) Note that `c` will be a list, not a string.

Inside the column loop, we reset `y` to the empty list by `Y`anking `l`. `Fxi` loops over `i`. In later iterations, `i` will be a list of the y-coordinates the player was able to reach in the previous column. The first time through, we want to start with just `0` (upper left corner). The variable is preinitialized to a Scalar `0`, not a List `[0]`, but Pip iterates over it just fine either way.

For each of the valid positions in the last column, `Ic@xQs` checks whether there is a space in that position in the current column. If not, the player just ran into a wall and we go on to try the next possibility. If so, then we want to find the positions the player will fall to in this column for each direction of gravity, and add them to the list `y` using the `P`ush`B`ack operator.

Gravity going up (left, in the transposed version):

```
(Jc@<x@?`# *$`)+1
  c@<x             Slice everything left of x in the column
 J                 Join into a string so we can do a regex search on it
      @?`# *$`     Find index of the last # in this string
(             )+1  The player's index is the space below/to the right of this #

```

Gravity going down (right, in the transposed version):

```
(c@>x@?'#)+x-1
 c@>x              Slice everything right of x in the column
     @?'#          Find index of the first # in this list (no need to join into string)
(        )+x       Translate to index number in entire column
            -1     The player's index is the space above/to the left of this #

```

If the player falls off the grid in a particular direction, the respective `@?` operation will not find a `#` and will give nil. This is not a valid index and will generate some warnings in the next iteration--which, however, are not visible without the `-w` flag. For our purposes, these cases are essentially eliminated from consideration.

After the inner loop, `i:UQy` takes the list `y` of positions we've built, eliminates duplicates, and assigns it to `i`. (Eliminating duplicates is necessary because otherwise the list balloons exponentially.) We then go to the next column. When we have looped through all columns, if there was a valid path through, `i` will be a nonempty list of positions (truthy); if not, it will be an empty list (falsey).
> 3 votes

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


title: Reverse Greek Conversion Golf

text:
# Question
Title: Reverse Greek Conversion Golf
### Introduction

You must create a function to convert Greek numerals into Arabic numerals. The input will be a Greek numeral less than `1000` and more than `0`. This is the reverse of my previous challenge.

### Algorithm

1. Split input into letters (e.g. `ΡΚΓ` -\> `Ρ`, `Κ`, `Γ`)
2. Take each letter, and change to character found in table below, for letter symbol, (e.g. `ΡΚΓ` -\> `Ρ`, `Κ`, `Γ` -\> `100`, `20`, `3`).
3. Add (e.g. `ΡΚΓ` -\> `Ρ`, `Κ`, `Γ` -\> `100`, `20`, `3` -\> `123`)

### Specifications

* No built-in number-system conversion
* Input will be capitalized as in example.
* Output must be in base 10.
* `ΡΡΡΡ` will never happen. It will be `Υ`.

### Test Cases

```
ΡΚΓ -> 123
Η -> 8
ΨΟΖ -> 777
Ρ -> 100
ΧϜ -> 606
ΡϘ -> 190
ΜΒ -> 42
Ν -> 50

```

### Table

```
Α = 1 = Alpha = 913 UTF-8
Β = 2 = Beta = 914 UTF-8
Γ = 3 = Gamma = 915 UTF-8
Δ = 4 = Delta = 916 UTF-8
Ε = 5 = Epsilon = 917 UTF-8
Ϝ = 6 = DiGamma = 988 UTF-8
Ζ = 7 = Zeta = 918 UTF-8
Η = 8 = Eta = 919 UTF-8
Θ = 9 = Theta = 920 UTF-8

Ι = 10 = Iota = 921 UTF-8
Κ = 20 = Kappa = 922 UTF-8
Λ = 30 = Lambda = 923 UTF-8
Μ = 40 = Mu = 924 UTF-8
Ν = 50 = Nu = 925 UTF-8
Ξ = 60 = Xi = 926 UTF-8
Ο = 70 = Omicron = 927 UTF-8
Π = 80 = Pi = 928 UTF-8
Ϙ = 90 = Koppa = 984 UTF-8

Ρ = 100 = Rho = 929 UTF-8
Σ = 200 = Sigma = 931 UTF-8
Τ = 300 = Tau = 932 UTF-8
Υ = 400 = Upsilon = 933 UTF-8
Φ = 500 = Phi = 934 UTF-8
Χ = 600 = Chi = 935 UTF-8
Ψ = 700 = Psi = 936 UTF-8
Ω = 800 = Omega = 937 UTF-8
Ϡ = 900 = SamPi = 992 UTF-8

```

# Answer
> 2 votes
# Jelly, ~~47~~ 45 bytes

```
⁵*×‘}
“#'nn(2jj33556;r”Or2/F+878Ọ
¢iÐ€’d9ñ/€S

```

Try it online! or verify all test cases.

# Answer
> 4 votes
# Python 3, 112

Saved 4 bytes thanks to vaultah.

Booyah, beating JS!

```
lambda x,z="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".find:sum((z(c)%9+1)*10**(z(c)//9)for c in x)

```

With test cases:

```
assert(f("ΡΚΓ")==123)
assert(f("Η")==8)
assert(f("ΨΟΖ")==777)
assert(f("Ρ")==100)
assert(f("ΧϜ")==606)

```

Loops through the string and uses its index in the list of potentials chars to calculate how much it's worth.

# Answer
> 3 votes
# JavaScript (ES7), 115 bytes

```
s=>[...s].map(c=>n+=((i="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".search(c))%9+1)*10**(i/9|0),n=0)|n

```

# Answer
> 3 votes
## Haskell, ~~116~~ 113 bytes

```
f x=sum[v|d<-x,(l,v)<-zip"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"$(*)<$>[1,10,100]<*>[1..9],d==l]

```

Usage example: `map f ["ΡΚΓ","Η","ΨΟΖ","Ρ","ΧϜ","ΡϘ","ΜΒ","Ν"]` -\> `[123,8,777,100,606,190,42,50]`.

Lookup the value of the greek letter from a list of pairs `(letter, value)` and sum. The list of values is build by `(*)<$>[1,10,100]<*>[1..9]`, where `(*)<$>[1,10,100]` builds a list of functions `[(*1),(*10),(*100)]` (multiply by 1, 10 and 100) which are applied separately to the elements of `[1..9]` and concatenated into a single list.

Edit: 3 bytes with thanks to @xnor.

# Answer
> 3 votes
# Julia, ~~82~~ 70 bytes

```
x->10.^((t=findin([1:5;76;6:16;72;17;19:25;80]+912,x)-1)÷9)⋅(t%9+1)

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 116 bytes

```
s=>[...s].map(c=>n+=+((i="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".search(c))%9+1+"e"+(i/9|0)),n=0)|n

```

Only 1 byte longer than ES7!

# Answer
> 1 votes
## Python 3, 188 Bytes

```
def f(x,l=list,z=0):
 r=l(range(1,10));R=[a*10for a in r]
 for a,b in l(zip(l("ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"),r+R+[a*10for a in R])):
  z+=(0,b)[a in x]
 return z

```

Try it out! (Test cases included)

# Answer
> 1 votes
# Retina, 72 bytes

```
T`_Ι-ΠϘ0ΡΣ-ΩϠ`dl
[a-j]
$0aa
\d
$&0
T`_Α-ΕϜΖ-Θl`dd
\d+
$*
1

```

Try it online.

### Explanation

Basically - replace every Greek symbol with the number that it represents, then return the sum of all the resulting numbers:

Transliterate `10`s digits to Arabic and `100`s digits to the Latin alphabet (`0`-`9` =\> `a`-`j`):

```
T`_Ι-ΠϘ0ΡΣ-ΩϠ`dl

```

Append "aa " to any `100`s digits:

```
[a-j]
$0aa

```

Append "0 " to any `10`s digits:

```
\d
$&0

```

Transliterate `1`'s digits and Latin alphabet to Arabic:

```
T`_Α-ΕϜΖ-Θl`dd

```

Convert all space-separated decimal numbers to unary:

```
\d+
$*

```

Count the total number of unary `1`s:

```
1

```

---
Tags: code-golf, number, natural-language, conversion
---


# Question
Title: What's my name? Produce the name of the language indirectly
Produce only the name of a programming language using only the facilities of the language itself. The name of the language can only be invoked indirectly, i.e., from non custom environment variables, built-in functions or methods or the interpreter/compiler of the language. Output should be the name of the language only.

One example would be:

```
$ awk --v | awk 'NR<2 { print $2}'  # GNU Awk 3.1.8
Awk

```

The answer I select will be the one with the most up votes. In case of a tie, the shortest golfed version (separate or the only given answer), will be the tie breaker.

# Answer
## BASH, ~~17~~ 7

```
bash -c 'echo $0'

```

or even

```
echo ${0#-}

```

if you already run bash :D

**update**: `"echo $0"` gets `$0` expanded first so `'echo $0'` is the correct answer.
> 18 votes

# Answer
## Whitespace

```
|

|
```
> 31 votes

# Answer
## C

```
#define d(x) x(#x[3])
void main(){d(putchar);}

```
> 26 votes

# Answer
## J,4

```
u:74

```

Having a short language name does kind of help.
> 23 votes

# Answer
# Python - 23 22

```
print`credits`[97:103]

```
> 23 votes

# Answer
# Python (win32) - abuse of the random module

I'm not sure whether this actually *works.* Depends on the implementation.

```
print ''.join([(random.seed(835)==None)and'']+[chr(random.randint(64,90)) for x in range(3)]+[(random.seed(53281)==None)and'']+[chr(random.randint(64,90)) for x in range(3)])

```
> 19 votes

# Answer
## BrainFuck

Just for fun (I know this isn't related to the purpose of the task.), I wrote this code...

```
+++++[><-+-+-><><>++<><>+++++<>+<]>>>+
+>><<+<>+><<>+[><-<<+>>><>+<><>++<]>[-<<<
+>>>]+<<+<[><->>+>><>+<<><+<<]>->-><>->
+++++<<>+++++<<>------>><>+.<<[-<>+<>->
+<]>>+><+<>><+><+[<]>-<><>-><<>-<<>+>-.<
+<><>+<>+[><>-<>-><<>-<>><-<><>-><><-+<
++---]>[+>]<<+><+.>><-<<+++++[>+<><><-]
>
+++.>+<+<>+++<>+.+>
-.<><+<+><+><><++>
+++<>+<+>>+<><>+<
+.<><+[->>+>><<++
+<>><++-<<-+-<>+]+
>
>
---.<
---
---
---
<>>
<-.
---
>-<

```

And when I replaced `<`,`>`,`[`,`]`,`.` with space...

```
+++++   -+-+-     ++    +++++  +     +
+    +  +    +   -  +     +    ++    -
+    +  +    -  +    +    +    - -   -
+++++   +++++   ------    +    -  +  -
+    +  +    +  +    -    -    -   + -
+    +  +    -  -    -    -    -    -+
++---   +    +  +    -  +++++  +     -

+++  + +  +++  + +
-    + +  +    ++
+++  + +  +    +
+    + -  +    ++
+    ++-  -+-  + +

---
---
---
---

 -
---
 -

```
> 17 votes

# Answer
**Piet, 47x2 pixels**

Using 5x5 codels:
> 13 votes

# Answer
## Python

```
import sys;print sys.copyright[24:30]

```

This also works for me (sys.executable is '/usr/bin/python')

```
import sys;print sys.executable[9:]

```
> 12 votes

# Answer
## brainfuck 101

```
++++++++[->++++++++++++>+>>++>+++<<<<<]>[->+>+>+>+<<<<]>+>++.>++.<-.<.>>----.<<---.>>>---.<<++.>---.

```

could probably be golfed slightly further, but it's 6am and I should get some sleep...
> 11 votes

# Answer
## **C**

In the spirit of Anon's answer in C (considering a C file always has the extension .c). I'd suggest :

```
#include <stdio.h>
void main(){puts(__FILE__+sizeof(__FILE__)-2);}

```
> 11 votes

# Answer
## Java

```
public class Name {
    public static void main(String[] args) {
        String s = "";
        s = s.getClass().getName();
        s = s.substring(0, 1).toUpperCase() + s.substring(1, 4);
        System.out.println(s);
    }
}

```
> 7 votes

# Answer
## C

Built using DevStudio 2005

```
#include <stdio.h>
void main ()
{
  int i,j,i2;
  for (i=j=0,i2=200;i2<=200;i2-=19,j==putchar(32|(i2<'Q'&&i2>'+'&&(j<20||i<12||i>28))*3)+8?j=0,i2+=i,i+=putchar('\n')-8:(i2+=j,j+=2));
}

```

Slightly shorter version (with compiler warnings)

```
int i,j,k;
for (i=j=k=0;k<=0;k-=19,j==putchar(32|(k<-119&&k>-157&&j<20|i<12|i>28)*3)+8?j=0,k+=i,i+=putchar('\n')-8:(k+=j,j+=2));

```
> 6 votes

# Answer
## Ruby - 27

```
puts RUBY_DESCRIPTION[0..3]

```

Update from Chris Jester-Young's comment:

## Ruby - 24

```
puts RUBY_COPYRIGHT[0,4]

```

Updated from Hauleth:

## Ruby - 15

```
p`ruby -v`[0,4]

```
> 6 votes

# Answer
## cat 3

Create a file with the following content (source code)

```
cat

```

And run it like (execute the file):

```
$ cat filename

```
> 5 votes

# Answer
# Clojure - 16 chars

```
(subs(str =)0 7)

```
> 5 votes

# Answer
## Haskell, 47

```
data H=Haskell deriving Show
main=print Haskell

```
> 5 votes

# Answer
# Ruby

Not short, but very indirectly.

```
4.times{|x|print((82+11.24*x+8.231*Math.tan(111.2*x)).floor.chr)}

```
> 5 votes

# Answer
### Ruby (17)

`p 1299022.to_s 36`

Outputs `"ruby"`
> 5 votes

# Answer
# Bash/Brainfuck/C

```
//bin/bash -c 'echo ${0##*/}'
#define p putchar
#define exit main(){p(p+67);p(10);}
exit
//++++++++[->++++++++++++>+>>++>+++<<<<<]>[->+>+>+>+<<<<]
//>+>++.>++.<-.<.>>----.<<---.>>>---.<<++.>---.

```
> 5 votes

# Answer
## Brainfuck

```
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++.
-----------------.
++++++++.
+++++.
--------.
+++++++++++++++.
------------------.
++++++++.

```
> 4 votes

# Answer
## Perl

```
$^X=~/([a-z]+)[^\/]+$/;print$1,$/

```
> 4 votes

# Answer
## Scala — 42

```
print(((1,1).getClass+"").substring(6,11))

```

**Update — 39 chars**

```
print(('a.getClass+"").substring(6,11))

```
> 4 votes

# Answer
**C - 34**

I don't have enough reputation to add this as a comment to the previous C entry. Same idea as above, but the filename can be anything.c

```
main(){puts(index(__FILE__,0)-1);}

```
> 4 votes

# Answer
## \>\<\> (Fish) (11)

Even better:

```
'>'::o2-oo;

```
> 4 votes

# Answer
## Visual Basic (version 6.0)

```
MsgBox Right(Error(458), 12)

```

## VBScript

```
On Error Resume Next
Err.Raise 458
MsgBox Right(Err.Description, 8)

```

## Both VB6 and VBScript

```
On Error Resume Next
Err.Raise 458
D = Err.Description
MsgBox Mid(D, InStr(2, D, "V"))

```
> 3 votes

# Answer
## QBasic (37)

I am using version 1.1 of the QBasic interpreter.

```
FOR x=0TO 5:?CHR$(PEEK(2588+x));:NEXT

```
> 3 votes

# Answer
**Lua 25 Chars**

```
print(arg[-1]:match"%w+")

```

Or, analogue to the J B's J solution 17 chars:

```
print"\76\117\97"

```
> 3 votes

# Answer
## GolfScript (13)

```
"#{$0[0..9]}"

```
> 3 votes

# Answer
## Racket (45)

```
racket -e "(display(substring(banner)10 17))"

```
> 3 votes

# Answer
## D(52)

using the extension of the source file

```
import std.stdio;void main(){write(__FILE__[$-1]);}

```
> 3 votes

# Answer
# Mathematica 39

This makes use of the `FullForm` name of the Mathematica icon.

```
StringTake[ToString[FullForm[\[MathematicaIcon]]],{3,13}]

```
> 3 votes

# Answer
## Windows PowerShell

```
$ShellId -replace '.*\.'

```
> 2 votes

# Answer
# PHP

```
php -v|php -r'echo fread(STDIN,3);'

```
> 2 votes

# Answer
## Assembler

Assembled using A86, generates a Windows .COM (tested on XP)

```
inc cx
push bx
push bx
inc bp
dec bp
inc dx
dec sp
inc bp
push dx
and al,72
mov ah,9
mov dx,si
inc sp
pop si
pop cx
int 21h
ret

```
> 2 votes

# Answer
## Groovy - 34

```
print "${''.metaClass.name}"[0..5]

```
> 2 votes

# Answer
# shell (Linux)

```
basename `readlink /proc/$$/exe`

```
> 2 votes

# Answer
# Java

```
import java.util.Random;
public class J {
    public static void main(String[] args) {
        Random r = new Random(-2134197984);
        String s = "";
        while (true) {
            int k = r.nextInt(27);
            if (k == 26) break;
            s += (char)('a' + k);
        }
        System.out.println(s);
    }
}

```

Inspired by this stackoverflow question.
> 2 votes

# Answer
## Ruby (36)

```
# ruby -v|ruby -e"puts gets.split[0]"

```
> 1 votes

# Answer
**BASH (39)**

```
bash --version | head -1 | cut -d, -f1
GNU bash

```

if bash is required output then its 55 chars

```
bash --version | head -1 | cut -d, -f1 | cut -d" " -f2
bash

```
> 1 votes

# Answer
## JavaScript

Both of these include the "Script" part of JavaScript as a string literal. Could someone suggest a way to derive that part from the DOM when no script elements exist in the document?

### JavaScript was named after Java (77)

```
for(i in navigator)i[4]=='E'&&alert(i[0].toUpperCase()+i.slice(1,4)+'Script')

```

### Script elements have a "language" attribute (218, works in Chrome/Safari only)

```
u=123;for(w=l=97;w<u;++w)for(x=l;x<u;++x)for(y=l;y<u;++y)for(z=l;z<u;document.write('<script language="'+n+'script">this._?alert(n[_=0].toUpperCase()+n.slice(1)+"Script"):_=1</script>'))n=String.fromCharCode(w,x,y,z++)

```
> 1 votes

# Answer
**VBScript**

```
set fso = CreateObject("Scripting.FileSystemObject")
msgbox split(fso.GetFile(Wscript.ScriptFullName).Type," ")(0)

```
> 1 votes

# Answer
## C, 25

The following should be in a file named `c.c`

```
main(){puts(__FILE__+2);}

```

alternate version, 27 chars:

```
main(){putchar(*__FILE__);}

```
> 1 votes

# Answer
# JavaScript/ECMAScript – 31, ~~35~~, ~~57~~

```
for(i in{ECMAScript:0})alert(i)

```

located in `JavaScript.html`, or `ECMAScript.html`:

~~`alert(location.href.substr(-15,10))`~~

~~`document.write(window.location.pathname.substr(-15, 10));`~~
> 1 votes

# Answer
## Python (27)

```
print str(copyright)[24:30]

```
> 1 votes

# Answer
## Python (win32)

### 68 characters

```
>>> import sys;print str.upper(sys.executable[12])+sys.executable[13:18]
'Python'

```

### 41 characters

```
>>> print __import__('sys').executable[12:18]
'python'

```
> 1 votes

# Answer
**Groovy ( JVM language )**

```
def a =  Closure.class.name
6.times { print a[it] }

```

Which prints `groovy` as output :D
> 1 votes

# Answer
## R, 11 chars

```
LETTERS[18]

```

Alternatively 54 characters, using a non custom environment variable:

```
strsplit(packageDescription("base")$Author,"")[[1]][1]

```
> 1 votes

# Answer
## C, 25

```
main(){printf("%X",12);}

```
> 1 votes

# Answer
**Smalltalk** Squeak/Pharo flavour **16** chars

```
self environment

```

In Smalltalk, the name of global name space is Smalltalk
> 1 votes

# Answer
# dc

Noticed this was missing so here's

```
Od*dP1-P

```
> 1 votes

# Answer
# php

Very late but php have more way to show itself.

```
ob_start();
phpcredits();
$c=ob_get_clean();
echo substr($c,0,3);

```
> 1 votes

# Answer
**Javascript**

Fiddle : http://jsfiddle.net/RU2kA/1/

Code should be run from a html page enclosed within the `script` tag that has a `type` attribute

```
var x = document.querySelector("script");alert(x.type.split("/")[1]);

```
> 1 votes

# Answer
# Node.js: 29 characters

```
console.log(process.argv[0])

```
> 1 votes

# Answer
# Java

```
class j {
    public static void main(String a[]){
        System.out.print(Character.UnicodeBlock.of(43392).toString().substring(0,4));
    }
}

```

The Character constant referenced is the Unicode block of Javanese, which contains the aksara Jawa characters traditionally used for writing the Javanese language. :)
> 1 votes

# Answer
## **C#**

```
        Console.WriteLine(typeof(CSharpCodeProvider).Name.Substring(0,6));

```
> 0 votes

# Answer
# Ruby(35)

Using the RUBY\_DESCRIPTION variable may be cheating a little, but I'm not using the string "ruby" at least.

```
puts RUBY_DESCRIPTION.split(' ')[0]

```
> 0 votes

# Answer
# PHP (24-25)

25 with Bash:

```
a=`php -v`&&echo ${a:0:3}

```

24 if we can omit `<?php`:

```
echo substr(__FILE__,-3)

```
> 0 votes

# Answer
## Haskell, 52

```
main=putStr$map(enumFrom 'G'!!)[1,26,44,36,30,37,37]

```

Could be shorter if the answer can be case insensitive. I chose to start at `'G'` because Haskell has no G's in its name, and `'G'` comes before `'H'` using `enumFrom`. This solution does not define anything other than `main`.
> 0 votes

# Answer
**Java**

```
public class Me {
    public static void main(String[] args) {
            System.out.println(System.class.toString().substring(6, 7).toUpperCase() + System.class.toString().substring(7, 10));
    }
}

```
> 0 votes

# Answer
# Erlang, 21 chars

```
[H|_]=pre_loaded(),H.

```

Run in the interactive shell. This works in R14B02 but I don't know if the Erlang module will always be first in the list.
> 0 votes

# Answer
## Objective-C - 151 Chars

Little bit of trickery by taking the class name of NSObject, and chopping off the 'NS'

```
id s=[NSMutableString stringWithFormat:@"%@",[NSObject class]];
[s deleteCharactersInRange:NSMakeRange(0,2)];NSLog(@"%@%c%c%c%c%c",s,105,118,101,45,67);

```
> 0 votes

# Answer
# Element, 30 characters

```
2'116 110[2:1-+'101"]7'69[,#`]

```

Element is a language of my own design. For some limited documentation, you can look here. For the source to an Element interpreter written in Perl, you can look here.

Here is a walkthrough of how it works:

```
2` stores a 2 onto the control stack for later use
116 110 push those values (t and n) onto the stack
[ start a for loop that is repeated twice
   2: duplicate the 110
   1-+ adds a negative one to the top copy of 110
   ' move the top copy to the control stack as temporary storage
   101 add the code for an e onto the stack
   " move the copy from the control stack back on top of the 101
] end the for loop, this loops takes advantage of the fact that n m l are in consecutive order and both have an e in between
7' push a 7 onto the control stack
69 push the code for an E onto the stack
[ start a for loop that executes 7 times
   , perform ->char / ->num conversion
   # throws away the top item on the stack since this is the item->num conversion
   ` pop and output the top item on the stack, since this is the needed item->char conversion
] end the for loop, which prints out the numbers in character form in reverse order, to spell "Element".

```
> 0 votes

# Answer
# Q (6 chars)

```
10h$81

```
> 0 votes

# Answer
## bc

```
ipv4=$(ipmaddr show lo ipv4 | tail -n1 | awk '{print $2}') && echo "ibase=10;obase=16;"$(echo "ibase=6;$((2**${#ipv4}))" | bc) | bc

```

Let's deconstruct it:

```
ipmaddr show lo ipv4
1:  lo
    inet  224.0.0.1

```

result is unexpected, I expected 127.0.0.1, but 224.0.0.1 is sufficient.

* `tail -n1` takes the last line.
* `awk '{print $2}'` only the ip, so **ipv4=224.0.0.1** now.
* `${#ipv4}` is the length of this String which is 9 (our magic number :) )
* `$((2**${#ipv4}))` 2^9 is 512 as we all know.
* `echo "ibase=6;$((2**${#ipv4})) | bc` interprets 512 as a number to the base 6, which is 188 in decimal
* `echo "ibase=10;obase=16;"188 | bc` converts it to hexadecimal, which is - surprise:

> bc

Note: A shorter solution should be

```
 echo "ibase=6;obase=16;512" | bc

```

for the right part of the &&, but somehow it doesn't work as expected.
> 0 votes

# Answer
## C, 39 chars

```
main(){putchar(2[(char*)strerror(0)]);}

```
> 0 votes

# Answer
# F♯ - 187 Char

I had some fun with this - even if it's not really golfed. I should come up with a cleverer way to obscure the 72 and 2 though

```
let a="It's like OCaml... But .net!"|>Seq.sumBy(fun a->System.Convert.ToInt32(a))
System.Console.Write(System.Convert.ToChar(a%72*2))
System.Console.Write(System.Convert.ToChar(a%72))

```
> 0 votes

# Answer
## C, obvious golfed solution

```
main(){putchar(67);}

```

Of course, it's not quite as short as the J version.
> 0 votes

# Answer
## SQL ~~33~~ 32

```
print substring(@@version,11, 3)

```

(tested with SQL Server 2008 R2 SP1)
> 0 votes

# Answer
## Perl - 19

Less perlish than the other perl answer, but shorter.

```
print substr $^X,-4

```
> 0 votes

# Answer
## Haskell 137

This uses a fairly interesting method of encoding strings. Thought I'd share it.

```
import Data.Char
main=
  (print. map chr . reverse . map last . takeWhile (not . null) . iterate (\x->zipWith subtract x$tail x))[50,-14,-31,-20,-7,0,108]

```

Bonus points to anyone who can explain why this works.
> 0 votes

# Answer
**PHP**

```
<?php
//first option use something that probably isn't available in windows installs
print substr($_SERVER['_'],-3) . "\n";

// this should work everywhere
print strtolower(substr(array_pop(array_filter(array_keys($_SERVER),'filterSELF')),0,3)) . "\n";
// uses the following function to filter out only 'PHP_SELF'
function filterSELF($toCheck){
    return (strlen($toCheck) == 8 && substr($toCheck,-5) == '_SELF');
}

```

both return php
> 0 votes

# Answer
## Nemerle, 57

```
Nemerle.IO.print(typeof(Option).FullName.Substring(0,7));

```
> 0 votes

# Answer
## Python

```
import sys
try: from StringIO import StringIO
except: from io import StringIO # py3
stdout = sys.stdout
sys.stdout = s = StringIO()
import this # yeah
sys.stdout = stdout
print(s.getvalue()[11:17])

```
> 0 votes

# Answer
# Common Lisp, 36 characters

```
(subseq(package-name *package*)0 11)
=> "COMMON-LISP"

```
> 0 votes

# Answer
# Perl

```
print$^X=~/([a-z]+)$/,$/;

```
> 0 votes

# Answer
# Rebol

```
copy/part at system/license 16 5

```

For Rebol 2 use:

```
copy/part at system/license 1 5

```
> 0 votes

# Answer
**Perl, 28**

```
print @a=(a..z)[15,4,17,11];

```
> 0 votes

# Answer
# Molecule, 2 bytes

```
;M

```

Pre-defined variables are awesome.
> 0 votes

# Answer
# Factor

Works always:

```
version-info " " split first print

```

The hacky way:

```
(command-line) first "." split >title print

```

All Factor source files end in `.factor`, so this just gets that and titlecases it. Won't work for compiled executables, probably.
> 0 votes

# Answer
## C#, lots of characters

```
class g
{
    static void Main()
    {
        var r = new System.Diagnostics.StackTrace(new System.Diagnostics.StackFrame(true)).GetFrame(0).GetFileName();
        System.Console.WriteLine(Microsoft.CSharp.CSharpCodeProvider.GetLanguageFromExtension(r.Substring(r.Length - 2, 2)).ToUpper());
    }
}

```

That's probably closer to the spirit of the problem, but this will also work, hard coding the file extension, and is probably still effectively following the guidelines:

```
class g
{
    static void Main()
    {
        System.Console.WriteLine(Microsoft.CSharp.CSharpCodeProvider.GetLanguageFromExtension(".cs").ToUpper());
    }
}

```
> -1 votes

# Answer
## iX2Web

```
**iX2001C3 934238Mwlp WDJXZWJ8Xz AJMA0K=*

```
> -1 votes

# Answer
# Go

This generates an indirect language name, i.e. Issue 9 (hey, it's not directly said - you need to know what this refers to). I think it's a valid name for Go, considering it has redirect on Wikipedia. For more information why Issue 9 is a valid name, please see https://code.google.com/p/go/issues/detail?id=9.

```
package main

import "fmt"

func main() {
    fmt.Println("Issue 9")
}

```
> -1 votes

# Answer
## Java

```
System.out.println("".getClass().getName().substring(0, 4));

```

:D
> -2 votes

# Answer
# PHP - 22/14

(assumes a file named 'php')

```
<?php echo __FILE__;?>

```

Down to 14 with short tags

```
<?=__FILE__;?>

```

And then

```
php ./php

```
> -3 votes

# Answer
## Javascript : 48

```
alert((function Javascript(){}+"").substr(9,10))

```
> -5 votes

---
Tags: popularity-contest
---


title: Sum of positive integers.

text:
# Question
Title: Sum of positive integers.
## Problem:

Given a set of integers, find the sum of all positive integers in it.

### Input:

* *t* – number of test cases \[*t* \< 1000\]
* On each of next *t* lines, an integer *N* \[-1000 ≤ *N* ≤ 1000\]

### Output

The program should output the sum of all the positive integers.

Check your code in online judge

### Score

Score is equal to size of source code of your program except symbols with ASCII code ≤ 32.

Here is the best score list: Python Best Scores (Best score is 29)

# Answer
# Whitespace, 0

I couldn't resist. `S`= space, `T`= tab, `N` = newline, all have ASCII codes \<= 32.

```
SSSSNSSSSNTTSSSSSTNTNTTNSSSNSSSSTNTTTNTSTNSSSSTNSSSSTNTTTSSSSTNTSSTTTSSSSSTSNTNTTSSSSTSNTTTNTTSNSSSSNSSSSTSNTTTSSSSNTTTTSSSTTSNSNSNNSSTNSSSSNTTTTNSTSSSSTSTSNTNSSNNN

```

Base64 encoded for easy copy & paste.

```
ICAgIAogICAgCgkJICAgICAJCgkKCQkKICAgCiAgICAJCgkJCQoJIAkKICAgIAkKICAgIAkKCQkJ
ICAgIAkKCSAgCQkJICAgICAJIAoJCgkJICAgIAkgCgkJCQoJCSAKICAgIAogICAgCSAKCQkJICAg
IAoJCQkJICAgCQkgCiAKIAoKICAJCiAgICAKCQkJCQogCSAgICAJIAkgCgkKICAKCgo=

```
> 34 votes

# Answer
# Element, 17 characters plus 1 space

```
_'[_ 2:n;0>[n~+]]`

```

This is my first constructed language. It is designed to be very compact and human-readable. All of the instructions are one character long and perform a single function.

Element has two stacks and a hash as memory structures. The two stacks are called the main stack and the control stack. The main stack is where arithmetic, I/O, and hash manipulation occurs. The control stack is where logic operations occur, and this stack controls the while and for loops.

The basic idea behind Element is that there is a hash that stores numbers/strings, while the stack is used to perform calculations on these numbers. The results to these calculation can then assigned a certain place in the hash for future use. The different contents of the hash are called elements, so it is similar to an array but can have non-numerical names.

EDIT: You can find an interpreter for Element (written in Perl) here.

Here is the list of operators: In some of these examples, m and n represent numbers already on the stack.

```
text  --pushes the string "text" onto the main stack
'     --pops from main stack and pushes onto control stack
"     --pops from control stack and pushes onto main stack
#     --pops from main stack and destroys
[]    --FOR statement (view the top number number from control stack and eval those many times)
{}    --WHILE (loop until top number on control stack is 0)
(     --pops from main stack, removes first character, pushes the remaining string onto stack, and pushes the removed character onto stack
)     --pops from main stack, removes last character, pushes the remaining string onto stack, and pushes the removed character onto stack
~     --pops from main stack, pushes contents of the element with that name
+-*/%^ --pops two most recently named elements, adds/negates/multiplies/divides/modulates/exponentiates them, and places the result on the stack
mn;   --pops m and n and assigns element n the value of m
mn@   --pops m and n and moves mth thing in stack to move to place n in stack
m$    --pops m and pushs size of m onto the stack
mn:   --pops m and n and pushes m onto the stack n times
mn.   --pops m and n and pushes m concatonated with n
m?    --pops m and pushes 0 onto control stack if m is '0' or and empty string, else pushes 1
\     --escapes out of next character, so it isn't an operator and con be pushed onto the stack
><=   --pops two numbers off of stack and tests, pushes 1 onto control stack if true and 0 if false
`     --pops from main stack and prints
&|    --pops two items from control stack, performs and/or respectively, and pushes result back onto control stack
!     --pops a number off of control stack, pushes 1 if 0 or empty string, 0 otherwise
_     --inputs a word and pushes onto main stack
m,    --pops m from main stack, coverts it to char and pushes, converts to num and pushes
Newlines and spaces separate different elements to be pushed onto the stack individually, but can pushed onto the stack using \

```

Here is a walkthrough of how the program works:

```
_'[    --take the first line of input, transfer it to the control stack, and start a for loop
_ 2:   --take one more line of input, and duplicate it so that there are two copies
n;     --take one copy and put into element n
0>     --push a zero onto the stack, remove the zero and the other copy of the input, and compare. A 1 will be placed on the control stack if the input was greater than zero, a 0 otherwise.
[      --starts another for loop if the comparison was true. This loop will be repeated once if the comparison was true and no times if it was false, so it is the same as an IF statement.
n~     --pushes n onto the main stack, then pops it ans replaces it with the contents of n, which is the number stored earlier
+      --takes the number and adds it to the running total, which is contained as the last item on the stack
]      --ends the inner for loop
]      --ends the outer for loop
`      --print the top item (also the only item) on the stack to output

```
> 13 votes

# Answer
# Perl, 31

```
<>;$i+=$_*($_>0)while<>;print$i

```
> 8 votes

# Answer
## Ruby 1.9.2, 37

```
p eval [*$<].join.gsub(/\A\d+|-\d+|\n/, '+0')

```

Call like ruby scriptname file\_with\_ints .
> 5 votes

# Answer
# Ruby, 52

```
t=gets.to_i;s=0;t.times{i=gets.to_i;s+=i if i>0};p s

```
> 5 votes

# Answer
# Haskell, 58

Properly operates on only `t` integers. Haven't run it against Spoj because I just don't care to register there.

```
f (x:l) = take x l
main = interact $ show . sum . f . map (max 0.read) . lines

```
> 5 votes

# Answer
## Perl, 33

```
<>;while(<>){$i+=$_ if$_>0}print$i

```

Although the space is necessary, so it seems odd not to count it. Oh well, the rules is the rules.

Hmm. I could probably get away with using a variable name which doesn't count towards the total either. The thing is, I'm not sure how I'd paste the code then.
> 4 votes

# Answer
## code in **C 89 characters**

---

```
x="%d";  main(b,a,t)  {
  for(scanf(x,&t);t;t--)
    {  scanf(x,&a); a>0?b+=a:a; }  printf(x,b-1);
       return 0; }

```

**I tried a lot to reduce my code less than 63 bytes, but i can reduce it only to 89 bytes. Please help me to reduce it to 63 bytes or even less.**
> 4 votes

# Answer
# Clojure, 71

```
(reduce + (filter pos? (map #(Integer/parseInt %) (next (line-seq *in*)))))

```
> 3 votes

# Answer
In memoriam Dennis M. Ritchie

## unix 57¹72:

```
n=$(head -n1 i); echo $(($(head -n $((n+1)) i | tail -n $n | grep -v "-" | tr '\n' '+')0))

```

assuming i is the file, containing the ints.

¹) was wrong, included the number of lines, and added 1 line too less.

echo $(($(cat i | head -n $(head -n1 i) | grep -v "-" | tr '\n' '+')0))
> 3 votes

# Answer
### Haskell, 51

```
main = interact $ show . f . lines
f (x:l) = foldl (+) 0 $ map read l

```

(extra spaces for clarity, since they don't count)

Haskell is ... interesting, since you tend to get programs with a significant number of necessary spaces.
> 2 votes

# Answer
**C,88**

---

```
x="%d";  main(b,a,t)  {
for(scanf(x,&t);t--;)
{  scanf(x,&a); a>0?b+=a:0; }  printf(x,b-1);
return 0; }

```

---

**After another big effort, code is one character less, please help me to reduce it more.**
> 2 votes

# Answer
# Befunge-98 (24)

(Make sure you use an interpreter that can read negative numbers (seems to be a somewhat common bug, but RcFunge works))

```
<;-1\+*`0:&\_\#;.@;:;#&0

```

# Perl (25)

(Perl allows control characters in variable names, I named my variable ^B (ASCII 2) so that it does not count towards the goal.)

```
<>;$***^B***+=$_*!/-/for<>;print$***^B***
```

(Normal variant (27 chars)):

```
<>;$B+=$_*!/-/for<>;print$B

```
> 2 votes

# Answer
### APL (10)

```
+/{0⌈⎕}¨⍳⎕

```

Explanation:

* `⍳⎕`: read a line, gives a list \[1..N\] for user's input N
* `¨`: for each element in this list... (i.e. do N times)
* `0⌈⎕`: read a line, return the maximum of 0 and the entered N
* We now have a list with all positive Ns the user entered, and 0s where the user entered something negative.
* `+/` gives the sum of this list.
* The result is output by default (because we're not doing anything else with it).
> 2 votes

# Answer
**Mathematica: 18 16**

```
Boole[#>0]&/@x.x

```
> 2 votes

# Answer
## PowerShell, 44

```
($i=$input|%{+$_})[1..$i[0]]-gt0-join'+'|iex

```
> 1 votes

# Answer
## Q,12

```
{0+/x(&)x>0}

```

sample usage

```
q){0+/x(&)x>0} 1 -1 2 3 -1
6

```
> 1 votes

# Answer
# C, 70 72 characters

```
s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",s?&i:&c);printf("%d",s-1);}

```

The results on the SPOJ site definitely seem unreal - I have no idea how to get this down to 63.

However, **68** characters is reachable on some compilers by abusing undefined behaviour. The following works on x86 Linux with 32-bit gcc, on which all arguments are passed on the stack.

```
s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",&i+!s);printf("%d",s-1);}

```
> 1 votes

# Answer
## befunge, 3524

```
:0`j&1-\&:0`*+\:0`3*j$.@

```

with a little inspiration by seeing marinus answer, I've also managed 24 characters. but I've got a completely different approach.
> 1 votes

# Answer
# PYTHON 2.x, 50 chars

```
r=input
print sum(i for i in (r() for j in range(r())) if i>0)

```
> 1 votes

# Answer
## excel, 27

```
=SUM(INDIRECT("A2:A"&1+A1))

```

count t in A1, rest of data a2 and down
> 1 votes

# Answer
## Clojure, 108

```
(let [[n & m] (->> *in* java.io.BufferedReader. line-seq (map read-string))]
  (->> m (take n) (filter pos?) (apply +) println))

```

I really wish I could avoid the `java.io.BufferedReader.` part, since it costs 24 chars itself. But AFAIK there's no facility to read lines from STDIN without it.
> 1 votes

# Answer
# Perl, 20

I know it is old and trivial, but the Perl answer can be still improved:

```
#!perl -p
$.<2or$\+=$_*!/-/}{

```
> 1 votes

# Answer
## C

```
void main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
     {
     if(i>0)
     sum=sum+i;
     }
printf("sum of positive numbers is %d",sum);
}

```
> 0 votes

# Answer
### scala ~~55~~ 54:

```
println ((for (r <- 1 to readInt;
  i=readInt;
    if i>0) yield i)sum)

```
> 0 votes

# Answer
C++:

```
#include<iostream>
using namespace std;
int main()
{
    int c,n,s=0;cin>>c;
    while(c--)
    {
        cin>>n;s+=n*(n>0);
    }
cout<<s;return 0;
}

```

115 characters long. Need to optimize it to 90. Any suggestions ?
> 0 votes

# Answer
## PHP, 71

```
<?for($s=0,$t=fgets(STDIN)+0;$t--;$s+=($n=fgets(STDIN))>0?$n:0);echo$s;

```
> 0 votes

# Answer
### Python: (92 characters)

```
t = int(raw_input())
n = [int(raw_input()) for i in range(t)]
print(sum([n[i] for i in range(t) if n[i]>0]))

```
> 0 votes

# Answer
# C#

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
 static class Program
 {
   static void Main(string[] args)
   {
     Console.WriteLine(Console.In.ReadToEnd().Split('\n').Sum(l => { Int32 v; return Int32.TryParse(l, out v) ? v.To(1000).Where(x => x > 0).Sum() : 0; }));

    }
    static IEnumerable<int> To(this int a, int b) { for (var i = a; a <= b; a++) { yield return i; } }
  }
}

```
> 0 votes

# Answer
## Ruby, 42

```
s=0
gets.to_i.times {
    i=gets.to_i
    s+=i if i>0
}
p s

```

(based on david4dev's answer)

Best score for Ruby on spoj: http://www.spoj.com/ranks/SIZECON/lang=RUBY
> 0 votes

# Answer
# 45 chars in python

```
c=0
j=input
for i in j()*[0]:
    b=j()
    c+=b*(b>0)
print c

```
> 0 votes

# Answer
# Python 3, score: ~~63~~ 61

```
r=0
q=input
w=int
for i in[1]*w(q()):
 t=w(q())
 r+=t+abs(t)
print(r/2)

```

I don't really know python, so I'm having a considerably difficult time making this any smaller.

# Python, score: ~~49~~ 48

```
r=0
q=input
for i in[1]*q():
 t=q()
 r+=t+abs(t)
print r/2

```

Same as above, but python 2 doesn't need the casting to int, apparently.
> 0 votes

# Answer
## Perl, 30

so close to that python best of 29, but had to add +1 for the `-p` switch

```
$s.=$_}{$s=~s/\s\d+/$_+=$&/eg

```
> 0 votes

# Answer
# Python

One-statement Solution

## Python 3 (60 chars, 66 with spaces)

```
print(sum(x for x in(int(input())for _ in[1]*int(input()))if x>0))

```

## Python 2 (48 chars, 55 with spaces)

```
print sum(x for x in(input()for _ in[1]*input())if x>0)

```

May be shortened by one character

```
i=input
print sum(x for x in(i()for _ in[1]*i())if x>0)

```
> 0 votes

# Answer
# dc, 22 chars

```
0?[sa?+la1-d0<b]dsbxrp

```

Negative numbers must be specified in the `dc` notation, i.e. with underscore: `_20`.
> 0 votes

# Answer
# PERL, 21 chars (score 20)

```
$a+=<>for 1..<>;say$a

```
> 0 votes

# Answer
# Smalltalk, 79

```
b:=[:x|Number readFrom:Stdin].(((1 to:(b value:1))collect:b)select:[:i|i>0])sum

```
> 0 votes

# Answer
## **Python, 41**

```
i=input
print sum(len(" "*i())for j in[0]*i())

```

## **Python, 42**

```
c=""
i=input
exec'c+=" "*i();'*i()
print len(c)

```
> 0 votes

# Answer
## Windows Batch, 68 (characters \>= 32)

I was about to post an extremely simple solution, but then I realised you have to read the number of test cases. Initially I just had `for %%a in (%*)do set/a"i+=%%a"` `echo %i%`.

```
set/p t=
for /l %%i in (1 1 %t%)do call :a
echo %i%
:a
set/p N=
if %n% geq 0 set/a"i+=N"

```

It reads t, then each N from stdin.
> 0 votes

# Answer
# J - 22 char

All these inputs blowing up the character count. Envious of APL here...

```
+/0>.".1!:1#&1".1!:1]1

```

Explained:

* `1!:1]1` \- Read in a line of input (`1!:1`) from input (file handle `1`).
* `#&1".` \- Convert to an integer (`".`) and create a list of `1`s that long (`#&1`).
* `".1!:1` \- Read in a line for each `1` in the list, and convert them to integers.
* `0>.` \- Take the greater of each integer and 0, effectively zeroing the negative numbers.
* `+/` \- Sum all the integers together.

Usage:

```
   +/0>.".1!:1#&1".1!:1]1
3
11
909
-67
920

```
> 0 votes

# Answer
# K - 20 char -2 = 18 pts

Had two 20 char solutions, and this one has more whitespace.

```
(. 0:`){x+0|. 0:`}/0

```

Explained:

* `n f/0` \- Apply the function `f` to 0, `n` times.
* `(. 0:`)` \- Read in a line (`0:`) from input (file handle ```) and convert to integer (`.`).
* `{x+0|. 0:`}` \- Read in an integer (`. 0:``), take the greater of it and zero (`0|`), and add it to the argument (`x+`).

Usage:

```
  (. 0:`){x+0|. 0:`}/0
4
123
-99
12
9
144

```
> 0 votes

# Answer
# JavaScript 93

Works for *t* integers, but said integers need to be entered with spaces in between.

`y=(x=prompt().replace(/-\d{1,4}/g,"").replace(/ /g,"")).length;for(s=0;y--;)s+=+x[y];alert(s)`

Takes the prompt, strips negative numbers and spaces, and adds the numbers...
> 0 votes

# Answer
# Pyth \- 7

Input in pyth is only one line, so it accepts comma-delimited instead of newline delimited. Pyth is not on Spoj, but there wasn't any rule saying it had to be.

```
sf>TZtQ

```

Very simple:

```
s      sum
f      filter by
>TZ    filter arg greater than zero
tQ     run filter on all but first element of evaluated input

```
> 0 votes

# Answer
# C#, score: 174

```
using System;

class P
{
    static void Main(string[] a)
    {
        uint s = 0, t, n;
        for (uint.TryParse(Console.ReadLine(), out t); t-- > 0; uint.TryParse(Console.ReadLine(), out n), s += n) ;
        Console.WriteLine(s);
    }
}

```
> 0 votes

# Answer
## C, 60 characters

There doesn't seem to be much to improve.

```
c;

main(x)
{
    while (0 < scanf("%d", &x))
        c += x * (x > 0);

    printf("%d", c);
}

```
> 0 votes

# Answer
# Factor, 95 bytes

```
[ [ readln dup string>number ] [ string>number dup [ 2 * ] [ ] if ] produce [ 0 max ] map sum ]

```

Like a lambda; use it with `call`.
> 0 votes

# Answer
# C++ (96 points)

```
#include<iostream>
main()
{
int t,n,s=0;
for(std::cin>>t;t;std::cin>>n, --t, n>0?s+=n:s);
std::cout<<s;
}

```
> -1 votes

# Answer
# Python, 43

```
c=0
i=input
exec'b=i();c+=b*(b>0);'*i()
print c

```
> -1 votes

# Answer
**Python 52 Characters**

```
c = 0
for i in range(t):
    k = input()
    if k>0:
        c+=k
print c

```
> -1 votes

---
Tags: code-challenge
---


title: How many 14ers did I climb?

text:
# Question
Title: How many 14ers did I climb?
In mountaineering terminology, a "14er" is any mountain with an elevation of 14 000 feet or more. However, there is another distinction. For a peak to count as a 14er, it must also have a "geographic prominence" of 300 or more feet. This means that to move from one 14er to another, you must first descend *at least* 300 feet before rising again. Take this example. Line 1 counts as 14 000 feet, and each line counts as 100 feet.

```
  /\__/\
 /      \
/        \

```

Now, both of these peaks have enough elevation to count, but there isn't enough drop in elevation between them to count as two separate peaks. Therefore, one of these counts as a 14er, and the other one is just a "partial peak". Here is an example where the two peaks count as two separate 14er:

```
   /\    /\
  /  \  /  \
 /    \/    \
/            \

```

There can also be a partial peak on the decline between two 14ers. Here's a slightly modified version of the last mountain range:

```
   /\      /\
  /  \/\  /  \
 /      \/    \
/              \

```

This mountain range also counts as two 14ers.

You must write a program or function that takes an ascii-art representation of a mountain range, and return how many 14ers are in the range. You can take input in whatever format is most convenient for you, be it 2D array of characters, a string with newline, or a string with some other delimiter. You can assume that all inputs will only contain the characters `/\_`, and that the length of each line will be the same (including trailing spaces). You can also assume that the mountain range starts on the bottom left corner with either a `/` or a `_`.

If the last section of a mountain is not on the bottom line, you can assume that the mountain only decreases after that, e.g.

```
  /
 /
/

```

Counts as a single 14er.

You do not have to handle invalid mountain ranges.

Here is some sample I/O:

```
         /\___/\_
        /        \    /\
       /          \  /  \
   _/\/            \/    \
  /                       \
 /                         \
/                           \_

2

                  /\    /\
         /\      /  \  /
  /\    /  \    /    \/
 /  \  /    \  /
/    \/      \/

4

       /\
 _/\__/  \
/         \

1

      /\
     /  \   /\
    /    \_/  \
   /           \
  /             \
 /               \
/                 \

1

              /\
    /\_/\    /  \_
   /     \  /     \     /\
  /       \/       \   /
 /                  \_/
/

3

```

# Answer
> 1 votes
# JavaScript (ES6), 133 bytes

```
s=>[...s].map((_,i)=>(c=s[i%h*w+i/h|0])=="/"?++a>2&&(p+=!d,d=a=3):c=="\\"&&--a<1&&(d=a=0),w=s.search`
`+1,h=-~s.length/w,a=3,d=p=1)|p

```

## Explanation

Since the specifications are not stated clearly, this makes a couple of assumptions:

* The bottom line is the 14,000ft mark (so all positions on the grid are high enough to count as a peak).
* The grid starts at (or ascending) the first peak (since it's at least 14,000ft high already as per previous assumption).
* A separate peak counts only after descending 300ft *then ascending 300ft*.

Iterates over the character `c` of each column (specifically, it iterates down each column until it finds a character). The current altitude is stored in `a`. It is clamped to a minimum of `0` and a maximum of `3`. The direction needed to move to count the next peak is stored in `d` (`false` = up, `true` = down). If `a` reaches `3` and `d` is `false`, the number of peaks `p` is incremented and `d` is set to `true` (down). Once `a` reaches `0`, `d` is set back to `false` (up).

```
var solution =

s=>
  [...s].map((_,i)=>   // loop
    (c=s[i%h*w+i/h|0]) // c = current character (moves down columns)
    =="/"?             // if c is '/'
      ++a>2&&          // increment a, if a equals 3 and d is true:
        (p+=!d,d=a=3)  // increment p, set d to true, clamp a to 3
    :c=="\\"&&         // if c is '\':
      --a<1&&          // decrement a, if a equals 0:
        (d=a=0),       // set d to false, clamp a to 0

    // Initialisation (happens BEFORE the above code)
    w=s.search`\n`+1,  // w = grid width
    h=-~s.length/w,    // h = grid height
    a=3,               // a = current altitude (min = 0, max = 3)
    d=                 // d = required direction (false = up, true = down)
    p=1                // p = number of found peaks
  )|p                  // output the number of peaks

var testCases = [`
/\\
`,`
/\\
  \\
   \\    /\\
    \\  /  \\
     \\/    \\
`,`
\\    /
 \\  /
  \\/
`,`
            /\\
         /\\/  \\/\\
      /\\/        \\/\\
   /\\/              \\/\\
/\\/                    \\/\\
`,`
  /\\__/\\
 /      \\
/        \\
`,`
   /\\    /\\
  /  \\  /  \\
 /    \\/    \\
/            \\
`,`
   /\\      /\\
  /  \\/\\  /  \\
 /      \\/    \\
/              \\
`,`
         /\\___/\\_
        /        \\    /\\
       /          \\  /  \\
   _/\\/            \\/    \\
  /                       \\
 /                         \\
/                           \\_
`,`
                  /\\    /\\
         /\\      /  \\  /
  /\\    /  \\    /    \\/
 /  \\  /    \\  /
/    \\/      \\/
`,`
       /\\
 _/\\__/  \\
/         \\
`,`
      /\\
     /  \\   /\\
    /    \\_/  \\
   /           \\
  /             \\
 /               \\
/                 \\
`,`
              /\\
    /\\_/\\    /  \\_
   /     \\  /     \\     /\\
  /       \\/       \\   /
 /                  \\_/
/
`];
result.textContent = testCases.map(c=>c+"\n"+solution(c.slice(1,-1))).join`\n\n`;
```

```
<textarea id="input" rows="6" cols="40"></textarea><br /><button onclick="result.textContent=solution(input.value)">Go</button><pre id="result"></pre>
```

# Answer
> 2 votes
# C, 174 bytes

```
a[99],c,p,j,M,m;main(i){for(i=j=1;c=getchar(),~c;i++)c<11?a[i]=j++,i=0:c&4?a[i]=j:0;for(m=j;c=a[i++];c>a[i-2]?M-m>1&&c-m>1?M=c,m=j,p++:M<c?M=m=c:M:m>c?m=c:0);printf("%d",p);}

```

Requires a trailing newline in the input, otherwise +4 bytes.

# Answer
> 1 votes
## JavaScript (ES6), 154 bytes

```
s=>s.split`\n`.map((s,i)=>s.replace(/\S/g,(c,j)=>{e[j]=i+(c!='\\');e[j+1]=i+(c>'/')}),e=[])&&e.map(n=>h-n+d?h-n-d*3?0:(c++,d=-d,h=n):h=n,h=e[0],c=d=1)|c>>1

```

Where `\n` represents the literal newline character. Ungolfed:

```
function climb(string) {
    var heights = [];
    // Split the array into lines so that we know the offset of each char
    var array = string.split("\n");
    // Calculate the height (actually depth) before and after each char
    for (var i = 0; i < array.length; i++) {
        for (var j = 0; j < string.length; j++) {
            switch (array[i][j]) {
            case '\':
                heights[j] = i;
                heights[j+1] = i + 1;
                break;
            case '_':
                heights[j] = i + 1;
                heights[j+1] = i + 1;
                break;
            case '/':
                heights[j] = i + 1;
                heights[j+1] = i;
                break;
        }
    }
    var count = 1;
    // Start by looking for an upward direction
    var direction = 1;
    var height = heights[0];
    for (var k = 1; k < heights.length; k++) {
        if (heights[i] == height - direction * 3) { // peak or trough
            direction *= -1;
            count++; // we're counting changes of direction = peaks * 2
            height = heights[i];
        } else if (heights[i] == height + direction) {
            // Track the current peak or trough to the tip or base
            height = heights[i];
        }
    }
    return count >> 1;
}

```

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


title: Regex Golf: Verify a Sudoku Solution

text:
# Question
Title: Regex Golf: Verify a Sudoku Solution
Write a regex which matches any valid sudoku solution and doesn't match any invalid sudoku solution. The input is an *unrolled* version of the sudoku, i.e. there are no line delimiters. E.g. the following board:

```
7 2 5 8 9 3 4 6 1
8 4 1 6 5 7 3 9 2
3 9 6 1 4 2 7 5 8
4 7 3 5 1 6 8 2 9
1 6 8 4 2 9 5 3 7
9 5 2 3 7 8 1 4 6
2 3 4 7 6 1 9 8 5
6 8 7 9 3 5 2 1 4
5 1 9 2 8 4 6 7 3

```

would be given as:

```
725893461841657392396142758473516829168429537952378146234761985687935214519284673

```

The rules are probably common knowledge by now, but just in case... a sudoku board is valid if and only if:

* Each row contains the digits from `1` to `9` exactly once.
* Each column contains the digits from `1` to `9` exactly once.
* Each of the nine 3x3 subgrids contains the digits from `1` to `9` exactly once.

## Rules

Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's `e` modifier).

You can use any regex flavour which existed before this challenge, but please specify the flavour.

Do not assume that the regex is anchored implicitly. E.g. if you're using Python, assume that your regex is used with `re.search` and not with `re.match`. Your regex does not need to match the entire string. It just needs to match at least one substring (which may be empty) for valid solutions and yield no matches for invalid solutions.

You may assume that the input will always be a string of 81 positive digits.

This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually `/.../`) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.

## Test Cases

Valid boards:

```
123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298
243561789819327456657489132374192865926845317581673294162758943735914628498236571
243156789519847326687392145361475892724918653895263471152684937436729518978531264
498236571735914628162758943581673294926845317374192865657489132819327456243561789
978531264436729518152684937895263471724918653361475892687392145519847326243156789
341572689257698143986413275862341957495726831173985426519234768734869512628157394

```

Invalid boards:

```
519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825
243561789829317456657489132374192865916845327581673294162758943735924618498236571
243156789529847316687392145361475892714928653895263471152684937436719528978531264
498236571735924618162758943581673294916845327374192865657489132829317456243561789
978531264436719528152684937895263471714928653361475892687392145529847316243156789
342571689257698143986413275861342957495726831173985426519234768734869512628157394
345678192627319458892451673468793521713524986951862347179246835534187269286935714
341572689257698143986413275862341957495726831173985426519234768734869512628517394

```

For further test cases, you can use this CJam script which takes a valid board as input and randomly shuffles it to give a new valid board (input format irrelevant as long as it contains only digits and optionally whitespace).

If your regex is compatible with the .NET flavour, you can test it online using Retina. A valid solution should print `0` for invalid boards and some positive integer for valid boards. To run all test cases at once, use this template and insert the regex on the second line. If you need regex modifiers, prepend a ``` to the regex and put the standard modifier letters in front of it.

# Answer
> 43 votes
# Ruby regex, 71 78 73 bytes

```
^(?!.*(?=(.))(.{9}+|(.(?!.{9}*$))+|(?>.(?!.{3}*$)|(.(?!.{27}*$)){7})+)\1)

```

I don't really know Ruby but apparently it doesn't complain about cascaded quantifiers.

Try it here.

# .NET regex, 79 78 75 or 77 bytes

Because Martin thinks this is possible... But I guess he will just incorporate these changes too.

```
^(?!(.)+((.{9})+|(?>(.{9})+
|.)+|(?((...)*
)(?>(.{27})+
|.){7}|.)+)(?<=\1))

```

Requires a trailing newline in the input to work. I'm not sure whether I'm allowed to do this (probably not).

Try it here.

The 77 byte sane version:

```
^(?!(.)+((.{9})+|((?!(.{9})*$).)+|(?((...)*$)((?!(.{27})*$).){7}|.)+)(?<=\1))

```

Thanks Neil for pointing out the error in my previous version and golfing off 1 byte (for the `(...)*`).

Try it here.

# PCRE, 77 78 bytes

```
^(?!.*(?=(.))((.{9})+|(.(?!(?3)*$))+|(?(?=.(...)*$)(.(?!(.{27})*$)){7}|.)+)\1)

```

Just for completeness.

Try it here.

Another version, also 78 bytes:

```
^(?!.*(?=(.))((.{9})+|(.(?!(?3)*$))+|(?>.(?!(...)*$)|(.(?!(.{27})*$)){7})+)\1)

```

Try it here.

### Explanation

```
^(?!.*                    # Match a string that doesn't contain the pattern,
                          # at any position.
  (?=(.))                 # Capture the next character.
  (
    (.{9})+               # Any 9*n characters. The next character is in
                          # the same column as the captured one.
  |
    (.(?!(.{9})*$))+      # Any n characters not followed by a positions 9*m
                          # to the end. The next character is in the same row
                          # as the captured one.
  |
    (                     # Any n occasions of...
    ?(.(...)*$)           # If it is at a position 3*k+1 to the end:
      (.(?!(.{27})*$)){7} # Then count 7*m characters that are not followed
                          # by a position 27*j to the end,
    |
      .                   # Else count any character.
    )+                    # The next character is in the same block as the
                          # captured one.
  )
  \1                      # Fail if the next character is the captured character.
)

```

# Answer
> 33 votes
# PCRE, 117 ~~119 130 133 147~~ bytes

```
^(?!(.{27})*(...){0,2}(.{9})?.?.?(.).?.?(?=(?2)*$).{6,8}(?3)?\4.{0,17}(?1)*$|.*(.)(.{8}(?3)*|((?!(?3)*$)(|.(?7))))\5)

```

~~Should also work in Python, Java, etc. flavors.~~ Now with recursion! And the "recursion" feature used non-recursively for "subroutines", which I totally forgot about until I had to use actual recursion.

# Answer
> 15 votes
# .NET regex, 8339 bytes

Yes, I know my solution is very naive, since Martin told me he did it in like 130 bytes. In fact, the URL to try it online is so long that I couldn't find a URL shortener that would accept it.

```
(code removed, since it's so long nobody will read it here,
and it made the post take forever to load. Just use the "Try it online" link.)

```

*The below link does not work in IE, but does work in Chrome and Firefox.*

**Try it online** \- All test cases at once, with the help of `!``  at the beginning, not included in byte count.

---

Here's the Python script I used to generate it (code below):

```
R=range(0,9)
S=range(1,10)

o = ""

# validate rows
T = "(?=.{%s,%s}%s)"
for j in R:
    for i in S:
        o += T % (9*j,9*(j+1)-1, i)

# validate columns
# "(?=(.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s})%s)"
T = "(?=("+"|".join([".{%s}"]*9)+")%s)"
for j in R:
    for i in S:
        o += T % (j,j+9,j+18,j+27,j+36,j+45,j+54,j+63,j+72, i)

# validate boxes
# (?=.{0,2}1|.{9,11}1|.{18,20}1)(?=.{3,5}1|.{12,14}1|.{21,23}1)
# (?=.{27,29}1|.{36,38}1|.{45,47}1)
T = ".{%s,%s}%s"
for i in S:
    for x in (0,27,54):
        for y in (0,3,6):
            o += "(?="+"|".join(T % (x+y+z,x+y+z+2, i) for z in (0,9,18))+")"

o += ".{81}"

o = o.replace(".{0}","").replace(",80}",",}")
print(o)

```

# Answer
> 14 votes
## .NET regex, 121 bytes

```
^(?!(.{27})*(.{9})?(...){0,2}.?.?(.).?.?(?=(...)*$)(.{9})?.{6,8}\4.{0,17}(.{27})*$|.*(?=(.))((.{9})+|(.(?!(.{9})*$))+)\8)

```

Explanation:

```
^(?!                     Invert match (because we're excluding duplicates)
 (.{27})*                Skip 0, 3 or 6 rows
 (.{9})?                 Optionally skip another row
 (...){0,2}              Skip 0, 3 or 6 columns
 .?.?(.).?.?(?=(...)*$)  Choose any of the next three cells
 (.{9})?                 Optionally skip another row
 .{6,8}\4                Match any of the three cells below
 .{0,17}(.{27})*$        As long as they're from the same square
|                        OR
 .*(?=(.))(              Choose any cell
  (.{9})+                Skip at least one row
 |                       or
  (.                     Skip cells
   (?!(.{9})*$)          Without reaching the end of the row
  )+                     For at least one cell (i.e. the cell chosen above)
 )\8)                    Match the chosen cell to the next cell
)

```

# Answer
> 8 votes
# PCRE, 3579 bytes

An absolutely terrible brute force solution. Negative lookbehinds ahoy!

I spent way too much time on this to abandon it, so here it is, for posterity's sake.

On the bright side, if Sudoku suddenly starts using a different set of 9 characters, this'll still work, I guess...

http://pastebin.com/raw/CwtviGkC

I don't know how to operate Retina, but you can also paste it into https://regex101.com or similar and it'll match.

Ruby code used to generate the regex:

```
# Calculate the block you're in
def block(x)
    x /= 3
    x + x%3 - x%9
end

81.times do |i|
    row, col = i.divmod(9)
    neg = []
    neg += (0...col).map {|e| 9*row + e + 1}
    neg += (0...row).map {|e| 9*e + col + 1}
    neg += (0...i).map {|e| e + 1 if block(e) == block(i)}.compact
    neg = neg.uniq.sort.map {|e| "\\#{e}"}
    if neg.size > 0
        print "(?!#{neg.join '|'})"
    end
    print "(.)"
end

```

# Answer
> 8 votes
## Ruby flavour, ~~75~~ 74 bytes

*Thanks to jimmy23013 for saving 1 byte.*

```
^(?!(.{9}*(.|(.)){,8}|.*(\g<2>.{8})*|.{27}?.{3}?(\g<2>{3}.{6}){,2}.?.?)\3).

```

Test it here.

Now that it's finally beaten, I can share my own solution. :) I discovered an interesting (maybe new?) regex technique in the process (the `(.|(.)){,8}\3` part), which would probably be unbeatable in cases where this can't be combined with other parts of the regex (as was the case in jimmy23013's answer).

### Explanation

Like the other short answers I'm using a negative lookahead which searches for duplicates in rows, columns or blocks. The basic building block of the solution is this:

```
(.|(.))...\3

```

Note that the `\3` is reused between three different alternatives (which all use group `3` for duplicate detection).

That group on the left (which is group `2`, containing group `3`) is used for any position that can contain the first half of a duplicate digit (within a group that must not contain duplicate digits). Then `...` is something that gets us the the next position where such a digit might occur (if necessary) and `\3` tries to find the second half of the duplicate via backreference. The reason this works is backtracking. When the engine first matches `(.|(.))` it will simply use `.` every time and not capture anything. Now the `\3` at the end fails. But now the engine will gradually try using `(.)` instead of `.` for individual matches. Ultimately, if there's a duplicate, it will find the combination where `(.)` was last used on the first digit of the duplicate (such that the capture isn't overwritten later), and then uses some more `.` to bridge the gap to the backreference. If there is a duplicate, backtracking will always find it.

Let's look at the three different parts where this is used:

```
.{9}*(.|(.)){,8}

```

This checks for duplicates in some row. First we skip to any row with `.{9}*`. Then we match up to 8 characters (i.e. anything in that row except the last digit) using the optional duplicate capture and try to find the `\3` after it.

```
.*(\g<2>.{8})*

```

This looks for duplicates in some column. First, note that `\g<2>` is a subroutine call, so this is the same as:

```
.*((.|(.)).{8})*

```

where the two groups we've just inserted are still referred to as `2` and `3`.

Here, the `.*` simply skips as far as necessary (it would be sufficient to match up to 8 characters here, but that costs more bytes). Then the outer group matches one complete row (which may wrap across two physical rows) at a time, optionally capturing the first character. The `\3` will be looked for right after this, which ensures vertical alignment between the capture and the backreference.

Finally, checking the blocks:

```
.{27}?.{3}?(\g<2>{3}.{6}){,2}.?.?

```

Again, the `\g<2>` is a subroutine call, so this is the same as:

```
.{27}?.{3}?((.|(.)){3}.{6}){,2}.?.?

```

To verify the blocks, note that since we've already checked all the rows and columns, we only need to check four of the 3x3 blocks. When we know that all rows and columns as well as these 3x3 blocks are correct:

```
XX.
XX.
...

```

Then we know that there can't possibly be duplicates in the remaining blocks. Hence I'm only checking these four blocks. Furthermore, note that we don't have to look for duplicates within the same row of a 3x3 block. It's enough to find the first half of the duplicate in one row and search for the second half in a row further down.

Now for the code itself, we first skip to the beginning of one of the four blocks with `.{27}?.{3}?` (optionally skip three rows, optionally skip three columns). Then we try to match up to two of the rows of the 3x3 block with the same trick we used for the rows earlier:

```
(.|(.)){3}.{6}

```

We allow but don't require capturing of any of the 3 cells in the current row of the 3x3 block and then skip to the next row with `.{6}`. Finally, we try to find a duplicate in either of the 3 cells of the row we end up on:

```
.?.?

```

And that's it.

# Answer
> 6 votes
# Javascript regex, ~~532~~ ~~530~~ ~~481~~ 463 chars

Validate rows:

```
/^((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$/

```

Validate columns:

```
/^((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9}/

```

Validate square from its first char:

```
/(?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)/

```

Set preview to start of the square:

```
/^(((?=)...){3}.{18})+$/

```

And the whole expression:

```
/^(?=((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$)(?=((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9})(((?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)...){3}.{18})+$/

```

Matches the whole string.

---

Test in Javascript ES6:

```
r = /^(?=((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$)(?=((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9})(((?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)...){3}.{18})+$/
;`123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298`
.split`
`.every(r.test.bind(r))
&&
`519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825`
.split`
`.every(s => !r.test(s))

```

---
Tags: code-golf, regular-expression, decision-problem, sudoku
---


title: Box-256 Assembly - BIG SQUARE II

text:
# Question
Title: Box-256 Assembly - BIG SQUARE II
*I'd like to start a series of challenges for http://box-256.com/ starting with the first challenge, “BIG SQUARE II”. After this one I'll add another for "CHECKERBOARD" and so on.*

**Rules**:

* Complete the BIG SQAURE II challenge in the Box-256 emulator (either on the website or download the program if you run Windows)
* Post back here a screenshot of your working answer
* You **MUST** include the code in plain text so that others can easily copy and very it’s operation.

**Scoring**:

The winner will be the least amount of instructions used (just the instruction calls, either by name or opcode, the arguments to them are not counted as JMP takes one argument but MOD can take three).

I think in the future contests we can add some additional bonus points for use of coding tricks and we could include the argument count too. I wanted to start basic to get the ball rolling.

**Winning**

I think we should put a stake in the ground and say two weeks from today we announce the winner(s, there maybe be mutliple entries with the same instruction count).

# Answer
> 4 votes
# 1 instruction

This solution is to illustrate that counting instructions is not a proper way of scoring for BOX-256.

```
JMP 002 072 00C
002 000 013 00C
001 00C 055 002
010 000 000 000
011 012 013 014
015 016 017 018
019 01A 01B 01C
01D 01E 021 022
023 024 025 026
027 028 029 02A
02B 02C 02D 02E
0D1 0D2 0D3 0D4
0D5 0D6 0D7 0D8
0D9 0DA 0DB 0DC
0DD 0DE 0E1 0E2
0E3 0E4 0E5 0E6
0E7 0E8 0E9 0EA
0EB 0EC 0ED 0EE
031 041 051 061
071 081 091 0A1
0B1 0C1 032 042
052 062 072 082
092 0A2 0B2 0C2
03D 04D 05D 06D
07D 08D 09D 0AD
0BD 0CD 0ED 03E
04E 05E 06E 07E
08E 09E 0AE 0BE
0CE 000 000 000

```

# Answer
> 9 votes
# 8 instructions

My smallest solution to the Big Square II challenge is 8 lines of code. There's a simple loop which cycles through a table of 8 pixel locations.

```
; Big Square II in 0x08h instructions
; John Metcalf

PIX @18 002 000
ADD @16 @18 @18
MOV @18 @20 001
MOV @19 @18 008
FLP @16 @17 001
JMP @00 001 010
011 031 021 032
0D3 01D 0E3 01E

```

# Answer
> 3 votes
# 11 instructions, 12 lines

```
PIX 011 002 000
ADD @01 @2C @01
ADD @03 001 @03
JGR 00D @03 @00
MOV 000 @03 000
ADD @06 001 @06
JGR 030 @06 @00
MOV 022 @01 000
MOV 02C @06 000
MOV 00B @0D 000
JMP @00 000 000
001 010 -01 -10

```

Any bonus for self-modification?

(Note the differences between the memory and the command line, specifically in locations `@01` `@06`, `@0D`.)

# Answer
> 0 votes
I think my answer is probably what you were suggesting @orlp ?

I've used 3 instrutions, PIX, ADD and JMP, the rest are the co-ordinates (however the instructions and coordinates are spaced out below for easier reading):

```
000 000 000 000
000 000 000 000
PIX @2C 002 000
ADD 001 @09 @09
JMP @08 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
011 012 013 014
015 016 017 018
019 01A 01B 01C
01D 01E 021 022
023 024 025 026
027 028 029 02A
02B 02C 02D 02E
031 032 03D 03E
041 042 04D 04E
051 052 05D 05E
061 062 06D 06E
071 072 07D 07E
081 082 08D 08E
091 092 09D 09E
0A1 0A2 0AD 0AE
0B1 0B2 0BD 0BE
0C1 0C2 0CD 0CE
0D1 0D2 0D3 0D4
0D5 0D6 0D7 0D8
0D9 0DA 0DB 0DC
0DD 0DE 0E1 0E2
0E3 0E4 0E5 0E6
0E7 0E8 0E9 0EA
0EB 0EC 0ED 0EE

```

---
Tags: graphical-output, atomic-code-golf, assembly
---


title: m-nomial coefficient

text:
# Question
Title: m-nomial coefficient
While the **binomial coefficient** are the coefficients of \\$(1+x)^n\\$, **m-nomial** coefficients are the coefficients of \\$(1+x+x^2+...+x^{m-1})^n\\$.

For example, \\$m(3,5,6)\\$ is the coefficient of \\$x^6\\$ in the expansion of \\$(1+x+x^2)^5\\$.

Write a program/function that takes 3 numbers as input and outputs the corresponding **m-nomial** coefficient.

### Details

* Input can be taken via any reasonable method.
* Everything out of range is \\$0\\$, for example \\$m(2,0,-1) = m(2,5,6) = 0\\$
* The first argument will be **positive**.
* The second argument will not be negative.
* All three arguments will be integers.

### Testcases

Inputs:

```
[1,0,0]
[2,5,6]
[3,5,6]
[4,5,-1]

```

Outputs:

```
1
0
45
0

```

### Scoring

This is . Shortest solution in bytes wins.

# Answer
# Jelly, 6 bytes

```
ṗ’S€ċ⁵

```

This is a full program that accepts **m**, **n** and the exponent as separate command line arguments.

Try it online!

### How it works

The problem boils down to counting the number of ways we can express the exponent as an ordered sum of exactly **n** integers between **0** and **m - 1** (both inclusive).

```
ṗ’S€ċ⁵  Main link. Arguments: m, n, k

ṗ       Cartesian product; yield the array of all lists of exactly n elements of
        [1, ..., m].
 ’      Decrement all integers in the resulting 2D list.
  S€    Compute the sum of each individual list.
     ⁵  Yield k.
    ċ   Count the number of times k appears in the list of sums.

```
> 6 votes

# Answer
# Perl, ~~63~~ ~~60~~ ~~59~~ 57 bytes

Includes +2 for `-pa`

Give input parameters on STDIN

```
mnomial.pl <<< "3 5 6"

#!/usr/bin/perl -pa
$_=/-/^($_--,1x$F[2])=~/^(1{0,$_}){$F[1]}$(??{++$;})/+$

```

As a perl programmer I just know that every problem is really a regex in disguise...

# Explanation:

m(3,5,6) can be seen as the number of ways you can get 6 by adding 5 integers in the range `[0..2]`. You can write a regex matching such a partition using:

```
1 x 6 = /^(1{0,2}){5}$/

```

However once a single solution is found the regex stops. We need to fail the found solution to get the regex to backtrack to the next solution and count the failures. In perl this can be done by extending the regex at runtime with something that is sure to fail, e.g. by demanding that something comes after the end of the string:

```
 1 x 6 = /^(1{0,2}){5}$(??{++$n})/

```

$n will count the number of failed attempts

My solution is basically this with two modifications:

* Output the counter in such a way that you get `0` instead of the empty string if there is no valid partition and the counter never gets incremented
* If the third argument is negative it would work if negative string lengths existed, but 1 x -5 is the empty string and 0 can be written exactly one way as sum of zeros, so that would output 1 instead of 0. I xor with the result of `/-/`to change the 1 back to 0

Without the need to handle a negative third argument this 49 byte solution would be good enough (give one parameter of `m(x,y,z)` on each line of STDIN in order `y \n z \n x \n`):

```
#!/usr/bin/perl -pa
$_=(1x<>)=~/^(1{0,@{[<>-1]}}){@F}$(??{++$;})/+$

```
> 7 votes

# Answer
# Pyth, ~~29~~ 8 bytes

```
/sM^UQEE

```

Try it online!

Uses Dennis' Method.

If the input can be rearranged so that `m(3,5,6)` is fed in the order of `6,3,5` into the program, an extra byte can be cut off:

```
/sM^UEE

```

Try it online!

### Original 29-byte approach

```
.N?|TY?|<Y0>Y*tNT0sm:NtT-YdN1

```

Test suite.

How it works:

Uses the recurrence formula `m(k,n,r) = m(k,n-1,r) + m(k,n-1,r-1) + ... m(k,n-1,r-k+1)`.

```
.N?|TY?|<Y0>Y*tNT0sm:NtT-YdN1
.N                             def colon(N,T,Y):
  ?|TY                             if T or Y:
      ?|<Y0>Y*tNT                      if Y<0 or Y>(N-1)*T:
                 0                         return 0
                                       else:
                  sm:NtT-YdN               return sum([colon(N,T-1,Y-d) for d in range(N)])
                                   else:
                            1          return 1

```
> 2 votes

# Answer
# Perl, ~~55~~ 51 bytes

Includes +2 for `-pa`

Same basic idea as my other Perl answer, finding partitions of an integer but with a completely different implementation. This version is shorter, but only because I don't have to special case a negative third argument.This version is also totally boring...

Give input for m(x,y,z) on STDIN with a line for each argument in order z, x, y. E.g. to calculate m(3,5,6):

```
 mnomial.pl
 6
 3
 5
 ^D

```

`mnomial.pl`:

```
#!/usr/bin/perl -pa
$"=",";$_=grep"@F"==eval,glob"+{@{[0..<>-1]}}"x<>

```
> 2 votes

# Answer
## Sage, 71 bytes

```
lambda a,b,c:(c>=0and(sum(x^i for i in range(a))^b).list()[c:]or[0])[0]

```

Verify all test cases online

The unnamed lambda function constructs the polynomial and returns the specified coefficient if `c` is not negative and less than or equal to the degree of the polynomial, else `0`.
> 1 votes

# Answer
# Python, 64 bytes

```
f=lambda m,n,k:(k==0)+sum(f(m,n-1,k-t)for t in range(m*(n>0<k)))

```

As far as code golf goes, this is fairly efficient. Test it on Ideone.
> 1 votes

# Answer
# Julia, ~~50~~ 45 bytes

```
f(m,n,k)=n>0?sum(t->f(m,n-1,k-t),0:m-1):0^k^2

```

Try it online!

If `digits` supported unary, the following approach would be 1 byte shorter.

```
g(m,n,k)=sum(t->k==sum(digits(t,m)),0:m^n-1)

```
> 0 votes

# Answer
## JavaScript (ES6), 118 bytes

```
(m,n,k)=>[...Array(n)].reduce(a=>a.map(x=>t+=x,t=0),[...Array(m*n+1)].map((_,i)=>i%m?0:i?x=-x*(n+1-i/m)*m/i:x=1))[k]|0

```

Works by calculating (xm-1)n/(x-1)n. (xm-1)n is calculated by the binomial theorem and the result is then repeatedly divided by x-1.

Edit: Saved 24 bytes by using a different binomial calculation. Saved 4 bytes by switching to `reduce` (yay!).
> 0 votes

---
Tags: code-golf, arithmetic, number-theory, combinatorics
---