title: My smartphone's phonebook

text:
# Question
Title: My smartphone's phonebook
## Introduction

Recently I was trying out one of the more obscure use-cases of a modern smartphone: Calling someone by number. While typing it in, I noticed that some of my phonebook entries were displayed, even though the number I was trying to call was different! After some experiments, I figured out why.

## What it does

Every entry in the phone book is examined like this:

* Split the entry by space into "words".
* Check every word like so:
    + For every digit in the number...
    + Is the character of the word at the current index on the key with the digit at the current number?
* If at least one such word exists, display this entry

## Challenge

Emulate my smartphone's behaviour!
Take the list of names below and a numeric string as input. The format for the phonebook may be chosen freely. Assume the phone number to always match `[0-9]*` and all names to match `[0-9a-zA-Z\s]+`

You can expect entries consisting of ASCII characters with values between 32 and 126 (including both). Your program should handle any length of entry and words within, as well as a list of any size.

Output a filtered list.

Input and output order is not relevant.

Use the following phone keyboard:

```
  1  |  2  |  3
     | abc | def
-----------------
  4  |  5  |  6
 ghi | jkl | mno
-----------------
  7  |  8  |  9
 pqr | tuv | wxy
  s  |     |  z
-----------------
     |  0  |
     |     |

```

## Rules

* This is , shortest code wins
* No standard loopholes

## Phone Book, values comma-seperated.

`noodle9, Kevin Cruijssen, Arnauld, RGS, xnor, Bubbler, J42161217, Neil, petStorm, fireflame241, Dennis, Martin Ender, Leaky Nun, Lyxal, HighlyRadioactive, Dingus, math, Beefster, Razetime, my pronoun is monicareinstate, Dom Hastings, Dion`

## Test cases

Input: 0815
Output: []

Input: 731
Output: []

Input: 532596
Output: []

Input: 53259
Output: [Leaky Nun]

Input: 542
Output: [J42161217]

Input: 27
Output: [Kevin Cruijssen, Arnauld]

Input: 36
Output: [Martin Ender, Dom Hastings]

Input: 6
Output; [noodle9, Neil, Martin Ender, math, my pronoun is monicareinstate, Leaky Nun]

Input: 3
Output; [Dennis, Martin Ender, fireflame241, Dingus, Dion, Dom Hastings]
```
</code></pre>

# Answer
# JavaScript (ES6), 102 bytes

Expects `(book)(digits)`, where `book` is an array of strings and `digits` is an array of integers. Returns an array of strings.

```
b=>a=>b.filter(s=>eval(`/\\b[${a.map(i=>i+"01adgjmptw"[i]+"-"+"01cfilosvz"[i]).join`][`}]/i`).test(s))

```

Try it online!

### How?

The sequence of digits is turned into a regular expression of the form:

```
/\b[Dx-y][Dx-y]...[Dx-y]/i

```

where `D` is the original digit and `x-y` is the letter range associated to it, or `D-D` for `0` or `1`.

For instance, `[2,7]` becomes `/\b[2a-c][7p-s]/i`.

We walk through the phone book and keep only the names that are matched by this regular expression.

### Commented

```
b => a =>             // b[] = book, a[] = integer sequence
b.filter(s =>         // for each string s in b[]:
  eval(               //   evaluate as JS code:
    "/\\b" +          //     regexp delimiter, followed by \b
    "[" +             //     followed by the first '['
    a.map(i =>        //     for each integer i in a[]:
      i +             //       append i
      "01adgjmptw"[i] //       append the first range character
      + "-" +         //       append a '-'
      "01cfilosvz"[i] //       append the second range character
    ).join`][` +      //     end of map(); join with ']['
    "]/i"             //     append the last ']' and '/i'
  )                   //   end of eval()
  .test(s)            //   keep s if it's matching the above regular expression
)                     // end of filter()

```
> 5 votes

# Answer
# Python 3, 96 bytes

```
lambda n,p:[s for s in p if' '+n in''.join([i,'%i'%min(ord(i)%32/3.2+2,9)][i>'9']for i in' '+s)]

```

Try it online!

Also works in Python 2

`ord(i)%32` converts both upper and lower case characters to the range `(1,2,3,...,24,25,26)`. Division by `3.2` converts this list to `00011122233344455556667778`. Adding `2` to the list and using `min` to convert the last digit into `9`, completes the character mapping `22233344455566677778889999`.
> 5 votes

# Answer
# 05AB1E, ~~34~~ ~~28~~ 20 bytes

```
ʒl1úA9L¦3и79ªS{‡I1úå

```

-8 bytes by porting *@SurculoseSputum*'s Python 2 answer, so make sure to upvote him as well!

First input is the list of contacts, second is the integer.

Try it online or verify all test cases.

**Original ~~34~~ 28 bytes answer:**

```
ʒlð¡εUεA•Ê_¢•6в<£yè«XNèå}P}à

```

First input is the list of contacts, second is the integer.

Try it online (the test case that results in my own name, I'm honored ^-^) or verify all test cases.

**Explanation:**

```
ʒ                # Filter the (implicit) input-list of contacts by:
 l               #  Convert the name to lowercase
  1ú             #  Pad the string with a single leading space
    A            #  Push the lowercase alphabet
     9L          #  Push a list in the range [1,9]
       ¦         #  Remove the first item to make the range [2,9]
        3и       #  Repeat the list 3 times: [1,2,3,4,5,6,7,8,9,1,2,3,...,9]
          79ª    #  Append 79 to the list: [2,3,4,5,6,7,8,9,2,3,4,...,9,79]
             S   #  Convert the list to a flattened list of digits:
                 #   [2,3,4,5,6,7,8,9,2,3,4,...,9,7,9]
              {  #  Sort the list: [2,2,2,3,3,3,...,8,8,8,9,9,9,9]
               ‡ #  Transliterate the alphabet to these digits in the contact-string
 I               #  Push the second input-integer
  1ú             #  Pad it with a single leading space as well
    å            #  And check if it's a substring of the transliterated contact-string
                 # (after which the filtered list of contacts is output implicitly)

```

```
ʒ                # Filter the (implicit) input-list of contacts by:
 l               #  Convert the name to lowercase
  ð¡             #  Split it on spaces to a list of words
                 #  (NOTE: `#` can't be used here, because it won't result in a list for
                 #   strings without spaces)
    ε            #  Map each word to:
     U           #   Pop the word and store it in variable `X`
     ε           #   Map the digits of the (implicit) input-integer to:
      A          #    Push the lowercase alphabet
       •Ê_¢•     #    Push compressed integer 13101041
            6в   #    Convert it to base-6 as list: [1,1,4,4,4,4,4,5,4,5]
              <  #    Decrease each by 1: [0,0,3,3,3,3,3,4,3,4]
               £ #    Split the alphabet into parts of that size:
                 #     ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
      yè         #    Index the current digit into this list
        «        #    Append the string to the current digit
         X       #    Push the current word `X`
          Nè     #    Index the map-index into it
            å    #    Check if this character is in the string (i.e. "abc2" and "c" → 1)
     }P          #   After the map: check if all digits were truthy
    }à           #  After the map: check if this was truthy for any word
                 # (after which the filtered list of contacts is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•Ê_¢•` is `13101041` and `•Ê_¢•6в` is `[1,1,4,4,4,4,4,5,4,5]`.
> 3 votes

# Answer
# Python 2, ~~129 111~~ 108 bytes

```
lambda n,S:[s for s in S if" "+n in"".join([`(ord(c)+(c<"S")-(c>"Y"))/3-20`,c][c<"A"]for c in" "+s.upper())]

```

Try it online!

A function that takes in a phone number string and a list of names, and returns the list of matched names.

For each name, converts it to its digit string equivalent, then returns the name if the phone number is found inside that name's digit string. To make sure that the phone number only matches the start of a word in name, before matching, a space is prepended in front of the phone number and the name.

Example:

```
name : "Kevin Cruijssen"    -> " 53846 278457736" (notice the space at the start)
phone: "27"                 -> " 27"
" 27" in " 53846 278457736" -> True

```
> 3 votes

# Answer
# , ~~103~~ 102 bytes

*Edit: -1 byte by prepending `0`  (zero followed by space) to the contact name, instead of just  (space), since the zero without a preceding space can itself never be matched*

```
function(n,l,`~`=toString)l[grepl(paste("",n),chartr(~letters,~c(7:31%/%3.13,9),paste(0,tolower(l))))]

```

Try it online!

Same approach as Surculose Sputum's answer: convert phonebook to space-separated numbers & search for match.

**Commented code:**

```
find_contact=
function(n,l                # n=number, l=list of contacts
 ,`~`=toString)             # ~=alias to toString function
 l[                         # return all entries in the list of contacts...
  grepl(                    # ...for which there is a match for...
   paste("",n),             # ...the number with prepended space...
   chartr(                  # ...in the list made by swapping all...
    ~letters,               # ...lowercase letters for...
    ~c(7:31%/%3.13,9),      # ...digits from 2 to 9 in groups of 3 (or 4 for 7 and 9)...
    paste("",tolower(l))    # ...in the lowercase list of contacts with prepended spaces
  ))]

```
> 3 votes

# Answer
# Retina, 72 bytes

```
~(1G`
.
[$&$&-$&]
T`2-9`a\dgjm\pt\w`.-
T`2-9`cfi\l\os\vz`-.
^
Gi`(?<=\W)

```

Try it online! Another port of @Arnauld's answer. Takes the first line as the digits and the remaining lines as the phone book. Explanation:

```
~(

```

Execute the rest of the program, then use the output as a program and execute that on the original input.

```
1G`

```

Keep only the line with the digits.

```
.
[$&$&-$&]

```

Turn each digit into a character class.

```
T`2-9`a\dgjm\pt\w`.-
T`2-9`cfi\l\os\vz`-.

```

Adjust the first and last characters of the range to the appropriate letters.

```
^
Gi`(?<=\W)

```

Prefix a Retina instruction to keep only lines matching those characters (case insensitively) when prefixed by a non-letter (therefore excluding the line of digits).

The result of the inner script looks something like this:

```
Gi`(?<=\W)[6m-o]

```

This is a Retina program to keep lines that match any of the characters `6mno` after a non-word character. Note that I can't include the non-word character in the match as that would cause the previous line to be included if the newline is the character in question.
> 2 votes

# Answer
# Jelly, 26 bytes

```
Œl>Ɱ“®K¿ʂ⁹FD»So⁸V€Ƥċ
ḲçƇ¥Ƈ

```

A dyadic Link accepting a list of the names on the left and a list of digits on the right which yields a list of names.

**Try it online!** (Footer formats the list, which when run as a full program gets implicitly smashed)

### How?

```
Œl>Ɱ“®K¿ʂ⁹FD»So⁸V€Ƥċ - Link 1: list of characters, word; list of integers, key-digits
Œl                   - lower-case
    “®K¿ʂ⁹FD»        - compressed string "AAcfilosv" ("AA"+"c"+"filos"+"v")
   Ɱ                 - map with:                       [ ...mmm filos :D ]
  >                  -   greater than?
             S       - sum
               ⁸     - chain's left argument, word
              o      - OR (vectorises) - i.e. replace 0s with word's digit characters
                  Ƥ  - for prefixes:
                V€   -   evaluate each as Jelly - i.e. cast any chars to ints
                   ċ - count (occurrence of key-digits) -> 1 if a prefix, else 0

ḲçƇ¥Ƈ - Main Link: list of lists of characters, names; list of integers, key-digits
    Ƈ - filter keep (names) for which:
   ¥  -   last two links as a dyad - i.e. f(name, key-digits):
Ḳ     -     split (name) at spaces
  Ƈ   -     filter keep (words) for which:
 ç    -       call last Link (1) as a dyad - i.e. g(word, key-digits)

```
> 2 votes

# Answer
# Java 8, 172 bytes

```
C->n->C.filter(c->{var s="(?i)";for(int i:n)s+="["+"01adgjmptw".charAt(i)+"-"+"01cfilosvz".charAt(i)+i+"]";var r=0>1;for(var w:c.split(" "))r|=w.matches(s+".*");return r;})

```

Port of *@Arnauld*'s JavaScript (ES6) answer, so make sure to upvote him as well!

Try it online.

**Explanation:**

```
C->n->              // Method with String-Stream & Integer-array parameters and String-Stream return-type
  C.filter(c->{     //  Filter the input String-Stream by:
    var s="(?i)";   //   Create a regex-String, starting at "(?i)"
    for(int i:n)    //   Loop over each digit of the input integer-array:
      s+=           //    Append the following to the regex-String:
         "["        //     An opening square bracket
         +"01adgjmptw".charAt(i)
                    //    Appended with the `i`'th character of "01adgjmptw"
         +"-"       //    Appended with a "-"
         +"01cfilosvz".charAt(i)
                    //    Appended with the `i`'th character of "01cfilosvz"
         +i         //    Appended with digit `i` itself
         +"]";      //    Appended with a closing square bracket
    var r=0>1;      //  Boolean `r`, starting at false
    for(var w:c.split(" "))
                    //  Split the current String by spaces, and loop over each word:
      r|=           //   Change the boolean to true if the following is true:
         w.matches( //    Check if the current word regex-matches:
           s        //     The regex-String we created earlier
           +".*");  //     Appended with ".*"
    return r;})     //  After the loop, return this boolean `r` to filter on

```

**Regex explanation:**

The `String#matches` method in Java implicitly adds a leading `^` and trailing `$` to match the entire String.

```
I.e. input [5,4,2] would result in the following regex:

^(?i)[a-c2][p-s7].*$
^                  $  # Match the entire string
 (?i)                 # Match case-insensitive
     [a-c             # A character in the range a-c (thus in "abc")
         2]           # or a 2 (thus in "abc2")
           [p-s       # Followed by a character in the range p-s (thus in "pqrs")
               7]     # or a 7 (thus in "pqrs7")
                 .*   # Followed by any amount of optional trailing characters

```
> 1 votes

# Answer
# Python 3, ~~242~~ ~~239~~ 237 bytes

```
def f(b,n,k=[]):
 x=[[k for k in j]for j in'0 1 abc2 def3 ghi4 jkl5 mno6 pqrs7 tuv8 wxyz9'.split()]
 for i in n:k=k and[p+j for p in k for j in x[i]]or x[i]
 return[u for u in b if sum(j==r[:len(j)]for j in k for r in u.lower().split())]

```

Try it online!

Explanation: Computes all possible strings that can be formed with the number and checks if any word in a name starts with any of those strings.
> 1 votes

# Answer
# Charcoal, ~~43~~ 42 bytes

```
ＳθＷＳ⊞υιΦυ№Ｅ⪪↥ι ⭆✂λ⁰Ｌθ¹⎇№ανΣＥ  CFILOSV›νπνθ

```

Try it online! Link is to verbose version of code. Takes input as the number and a newline-terminated list of phone book entries. Edit: Saved 1 byte by copying @JonathanAllan's digit conversion algorithm, which means that I get to use the `p` variable again. Explanation:

```
ＳθＷＳ⊞υι

```

Input the number and the entries. (These bytes could be removed by substituting a more cumbersome input format.)

```
 υ                                  List of phonebook entries
Φ                                   Filtered where
      ι                             Current entry
     ↥                              Uppercased
    ⪪                               Split on spaces
   Ｅ                                Map over words
          λ                         Current word
         ✂ ⁰Ｌθ¹                     Sliced to input digits length
        ⭆                           Map over characters and join
               ⎇                    Ternary
                 α                  Uppercase alphabet
                №                   Count of (i.e. contains)
                  ν                 Current character
                       CFILOSV      Literal string `  CFILOSV`
                    Ｅ               Map over characters
                               ν    Word character
                              ›     Is greater than
                                π   Inner character
                   Σ                Take the sum
                                 ν  Else current character
  №                                 Count of (i.e. contains)
                                  θ Input digits
                                    Implicitly print

```
> 1 votes

# Answer
# Rust, ~~158~~ 154 bytes

```
|a,b|b.filter(move|x|x.split(|&b|b<33).any(|w|(0..).zip(a).all(|(j,&i)|j<w.len()&&(b"@CFILOSVZ".iter().fold(1,|a,&b|a+(b<w[j]&95)as u8)==i||48+i==w[j]))))

```

Try it online!

The code is a bit of a mess, with a sprinkle of `.iter()`, `&` and `move` here and there. The strings are represented as `&[u8]`s, as are the numbers pressed. Rust doesn't have regexes in its standard library, so I manually find the digit for each letter from the array `b"@CFILOSVZ"`. Case insensitivity is performed by bitmasking with `95` which is `0x5f = 0x7f - 0x20`. This transforms the lowercase chars to uppercase.

Some bytes were saved in the edit by switching from `b==32` to `b<33` and using `(0..).zip()` and indexing instead of `w.iter().zip()`.
> 1 votes

# Answer
# Scala, 118 bytes

```
n=>_.filter(_ split " "exists(_.matches("(?i)"+n.map(i=>s"[$i${"01adgjmptw"(i)}-${"01cfilosvz"(i)}]").mkString+".*")))

```

Try it online

A port of @Arnauld's JavaScript (ES6) answer.

A curried lambda of type `Seq[Int]=>Seq[String]=>Seq[String]`.
> 1 votes

---
Tags: code-golf
---


title: Is my Processor 32 or 64 bit?

text:
# Question
Title: Is my Processor 32 or 64 bit?
Not to be confused with Is my OS 32-bit or 64-bit.

This one is very simple, tell me whether or not my CPU supports 64-bit instructions. If my CPU supports 32-bit instructions, print '32', if my CPU supports 64 bit instructions, print '64', if my processor *naitively* supports other lengths of instructions, print 'other'.

Your program must run on both 32 and 64-bit instruction modes, and if interpreted run properly on both 32 and 64-bit interpreters.

Test cases:

Arch: x86, i386, i686, RiscV32
Output: '32'

Arch: x86-64, x64, x86\_64, RiscV64
Output: '3264'

Arch: R700
Output '32other'

The usual rules apply.

Best of luck!

# Answer
> 3 votes
# Bash \+ coreutils, ~~33~~ 25 bytes

```
lscpu|grep -Po '..(?=-b)'

```

Don't try it online! Won't work because the TIO sandbox doesn't support lscpu. Edit: Saved 8 bytes thanks to @DigitalTrauma.

# Answer
> 1 votes
# Rust, 45 bytes

```
||if std::usize::MAX>4294967295{3264}else{32}

```

Try it online! (Cross compile for 32-bit locally by installing a toolchain for i686. For example: `stable-i686-pc-windows-msvc`)

Can't really test this on any architectures that support "other" lengths of instructions, but this can be used to check for 32-bit or 64-bit architectures. This is shorter than the built-in way using `cfg!(target_pointer_width="64")`.

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


# Question
Title: How many ways to write N as a product of M integers?
Given an integer *N*, count how many ways it can be expressed as a product of *M* integers \> 1.

Input is simply *N* and *M*, and output is the total count of *distinct* integer groups. Meaning you can use an integer more than once, but each group must be distinct (`3 x 2 x 2` would not count if `2 x 2 x 3` is present).

**Constraints**

1 \< *N* \< 231
1 \< *M* \< 30

**Examples**

Input `30 2` gives output `3`, since it can be expressed 3 ways:

```
2 x 15
3 x 10
5 x 6

```

Input `16 3` gives output `1`, since there's only one distinct group:

```
2 x 2 x 4

```

Input `2310 4` gives output `10`:

```
5 x 6 x 7 x 11
3 x 7 x 10 x 11
3 x 5 x 11 x 14
3 x 5 x 7 x 22
2 x 7 x 11 x 15
2 x 5 x 11 x 21
2 x 5 x 7 x 33
2 x 3 x 11 x 35
2 x 3 x 7 x 55
2 x 3 x 5 x 77

```

Input `15 4` gives output `0`, since it cannot be done.

**Rules**

Standard code golf loopholes apply, along with standard definitions for input/output. Answers may be a function or full program. Built-in functions for factorization and/or partitioning are not allowed, but others are fine. Code is counted in bytes.

# Answer
> 5 votes
# Pyth \- 24 23 22 21 bytes

Not a complicated solution. Will be golfing more. Just takes cartesian product of lists and filters. Same strategy as @optimizer (I'm guessing because of his comment, didn't actually decipher that CJam) Thanks to @FryAmTheEggman for 2 bytes and trick with M.

```
Ml{m`Sdfqu*GHT1G^r2GH

```

Defines a function `g` with args `G` and `H`

```
M                    function definition of g with args G and H
 l                   length of
  {                  set (eliminates duplicates)
   m                 map
    `Sd              repr of sorted factors so can run set (on bash escape ` as \`)
    f                filter
     q      G        equals first arg
      u*GHT1         reduce by multiplication
     ^     H         cartesian product by repeat second arg
       r2G           range 2 to first arg

```

Worked on all test args except last, was too slow on that one but there is no time limit given.

# Answer
> 9 votes
# Python 3, 59

```
f=lambda N,M,i=2:i<=N and f(N/i,M-1,i)+f(N,M,i+1)or-~M==N<2

```

We count up potential divisors `i`. With the additional argument `i` as the lowest allowed divisor, the core recursive relation is

```
f(N,M,i)=f(N/i,M-1,i)+f(N,M,i+1)

```

For each `i`, we either choose to include it (possible as a repeat), in which case we divide the required product `N` by `i` and decrement `M`. If we don't, we increase `i` by 1, but only if `i<N`, since there's no use checking divisors greater than `N`.

When the minimum divisor `i` exceeds `N`, there's no more potential divisors. So, we check if we've succeeded by seeing if `M==0 and N==1`, or, equivalently, `M+1==N==1` or `M+1==N<2`, since when `M+1==N`, the mutual value is guaranteed to be a positive integer (thanks to FryAmTheEggman for this optimization).

This code will cause a stack overflow for `N` about 1000 on most systems, but you can run it in Stackless Python to avoid this. Moreover, it is extremely slow because of its exponential recursive branching.

# Answer
> 4 votes
# Ruby, 67

```
f=->n,m,s=2,r=0{m<2?1:s.upto(n**0.5){|d|n%d<1&&r+=f[n/d,m-1,d]}&&r}

```

Actually reasonably efficient for a recursive definition. For each divisor pair `[d,q]` of n, with `d` being the smaller one, we sum the result of `f[q,m-1]`. The tricky part is that in the inner calls, we limit factors to ones greater than or equal to d so that we don't end up double-counting.

```
1.9.3-p327 :002 > f[30,2]
 => 3
1.9.3-p327 :003 > f[2310,4]
 => 10
1.9.3-p327 :004 > f[15,4]
 => 0
1.9.3-p327 :005 > f[9,2]
 => 1

```

# Answer
> 2 votes
# CJam, 48 bytes

This can be a lot shorter but I have added certain checks to make it work for decent number of `M` on the online compiler.

```
q~\:N),2>{N\%!},a*{_,2/)<m*{(+$}%}*{1a+:*N=},_&,

```

Try it online here

# Answer
> 2 votes
## T-SQL ~~456~~ 373

I'm sure this'll break when the inputs are even close to being large.

Thanks to @MickyT for helping to save a lot of characters with CONCAT and SELECTing instead of multiple SETs.

```
CREATE PROC Q(@N INT,@M INT)AS
DECLARE @ INT=2,@C VARCHAR(MAX)='SELECT COUNT(*)FROM # A1',@D VARCHAR(MAX)=' WHERE A1.A',@E VARCHAR(MAX)=''CREATE TABLE #(A INT)WHILE @<@N
BEGIN
INSERT INTO # VALUES(@)SET @+=1
END
SET @=1
WHILE @<@M
BEGIN
SELECT @+=1,@C+=CONCAT(',# A',@),@D+=CONCAT('*A',@,'.A'),@E+=CONCAT(' AND A',@-1,'.A<=A',@,'.A')END
SET @C+=CONCAT(@D,'=',@N,@E)EXEC(@C)

```

# Answer
> 0 votes
# Jelly, 10 bytes

```
ḍƇ`ḊœċP€ċ⁸

```

Try it online!

Assumes that "Built-in functions for factorization and/or partitioning are not allowed" doesn't prohibit the `œċ` builtin, which is combinations with replacements. If this isn't allowed, we can use a Cartesian product builtin, which is allowed, for 12 bytes: `ḍƇ`ḊṗṢ€QP€ċ⁸`

## How it works

```
ḍƇ`ḊœċP€ċ⁸ - Main link. Takes n on the left and m on the right
 Ƈ         - Filter the integers, k, between 1 and n where the following is true:
ḍ          -   Does k divide...
  `        -   ...n?
           - This gives a list of divisors
   Ḋ       - Remove the first value, 1
    œċ     - Take all combinations of length m, with replacement
      P€   - Take the product of each
        ċ⁸ - Count occurrences of n

```

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


# Question
Title: How many of each pill to take to achieve the total daily dose
A drug comes in 5mg, 2.5mg, and 1mg sized pills. The drug is taken once a day. The total daily dose will be only one of the following (all in mg):

1, 2, 3, ... 20, 22.5, 25, 27.5, 30, 32.5, 35, 37.5, 40, 42.5, 45, 47.5, 50

In words: any whole number less or equal to 20, then at 2.5mg increments up to 50.

Your task is to determine how many pills of each size the patient should take to get to their total dose, minimizing the total number of pills they have to take.

Input: the total daily dose

Output: the respective number of 5mg, 2.5mg, and 1mg the patient needs to take, in any consistent format.

This is code golf. Fewest number of bytes wins.

Examples: (output is number of 1, 2.5, and 5 mg pills)

```
1 => [1, 0, 0]
4 => [4, 0, 0]
7 => [2, 0, 1]
19 => [4, 0, 3]
22.5 => [0, 1, 4]
40 => [0, 0, 8]

```

*Irrelevant: this is based on a true story. The drug is prednisone and I wrote a program to automate the production of a calendar for patients to use to titrate their doses, which is a challenging task for many elderly patients to do safely even if you give them written instructions. This challenge was part of the programming task.*

# Answer
> 13 votes
# , ~~53~~ 38 bytes

```
function(x)c(x%/%5,2*x%%1,(x<20)*x%%5)

```

Try it online!

Output is in the order (5mg, 2.5mg, 1mg).

For the 2.5mg pills:

* if the dose is an integer, we need 0 such pills. Indeed, 1 pill of 2.5 mg would not give an integer, and 2 pills of 2.5 mg can be replaced by a single 5mg pill
* if the dose `x` is not an integer, we need exactly 1 such pill (similar argument), and then we call the function with the integer `x-2.5`.

The number of 5 mg pills is the integer division of the input by 5.

Note that because the input is restricted, the 1 mg pills are never needed when the input is ≥20. If the input is \<20, the number of 1mg pills is given by taking the input modulo 5.

# Answer
> 9 votes
# Python, 27 bytes

```
lambda x:[x//5,x%1*2,x*6%5]

```

Try it online!

An improvement to Manish Kundu's Python 3 solution.

The new part is `x*6%5` for the last entry. The idea is to take the value mod 5 for whole `x`, but to give 0 for the non-integer doses, which are multiples of 2.5. To do this, we multiply by 6 before reducing mod 5. Because \\$ 6 \equiv 1\\$ modulo 5, multiplying by 6 leaves integers unchanged mod 5, but it turns multiples of 2.5 into multiples of 5, which then reduce to 0.

In the second entry, `x%1*2` could also be `x*2%2` as an equal-length alternative. This may be useful for porting, if a language's mod operation only works on whole numbers.

# Answer
> 5 votes
# Rockstar, ~~127~~ ~~120~~ ~~118~~ ~~110~~ 100 bytes

Borrowing Robin's logic.

Output order is `1, 2.5, 5` separated by newlines

```
listen to N
let F be N/5
turn down F
let M be N
turn down M
let M be N-M
say N-M*5-F*5
say M*2
say F

```

Try it here (Code will need to be pasted in)

```
listen to N       :Read input string into variable N
let F be N/5      :Divide N by 5 and assign to variable
turn down F       :Floor F
let M be N        :Assign N to variable M
turn down M       :Floor M
let M be N-M      :Reassign N-M to M
say N-M*5-F*5     :Output N-M*5-F*5
say M*2           :Output M*2
say F             :Output F

```

# Answer
> 5 votes
# Jelly, 10 bytes

```
d5ḞƑƇ;Ø.ṁ3

```

A monadic Link accepting the dosage which yields a list of numbers, `[#5, #1, #2.5]`

**Try it online!**

### How?

```
d5ḞƑƇ;Ø.ṁ3 - Link: dosage     e.g. 22.5     OR   23
 5         - five                  5             5
d          - div-mod               [4, 2.5]      [4, 3]
    Ƈ      - filter keep if:
   Ƒ       -   is invariant under:
  Ḟ        -     floor             [4]           [4, 3]
      Ø.   - [0, 1]                [0, 1]        [0, 1]
     ;     - concatenate           [4, 0, 1]     [4, 3, 0, 1]
         3 - three                 3             3
        ṁ  - mould like            [4, 0, 1]     [4, 3, 0]

```

# Answer
> 5 votes
# Brachylog, 25 bytes

This defines a verb that takes as input the list of pills like `[2, 1, 4]` and outputs the sum of the pills milligrams. As this is Brachylog, we can then give an output like `24.5` an ask for a solution for the input.

```
Ṫℕᵐ<ᵛ⁵⁰;[1.0,2.5,5.0]\×ᵐ+

```

Try it online! (Note: you have to give the output as a float, e.g. `20.0`.) Or try all possible inputs.

### How it works

```
 Ṫℕᵐ<ᵛ⁵⁰;[1.0,2.5,5.0]\×ᵐ+
 Ṫ                          the input is a triplet [A, B, C]
  ℕᵐ                        all elements are >= 0
    <ᵛ⁵⁰                    and less than 50 (just to give the search some bounds)
        ;[1.0,2.5,5.0]      append the list of pill sizes
                      \     transpose: [[A,1.0],[B 2.5],[C,5.0]]
                       ×ᵐ   map multiplication over it
                         +  sum the result

```

Some notes: because Brachylog will try counting the trailing numbers up (`0 0 48, 0 0 49, 0 1 0, 0 1 1, …`), this guarantees that the first hit is also the solution with the fewest pills. `1,2.5,5` is not possible as otherwise the search will skip `A = 0, C = 0` for whatever reason. Also, some day I'll find a better way to constrain numbers in `0 … X` than `ℕᵐ<ᵛX`

# Answer
> 4 votes
# , 22 bytes

Returns in pill order `5 2.5 1`, based on @Robin Ryder's answer

```
<.@%&5,(~:<.),5&|*20>]

```

Try it online!

### How it works

```
<.@%&5,(~:<.),5&|*20>]
                  20>] x greater than 20?
              5&|*     multiply with x mod 5
       (~:<.),         prepend (x != floored x)
<.@%&5,                prepend (divide x by 5 and floor)

```

# Answer
> 4 votes
# Excel, 64 bytes

```
=MOD(A1,5)-2.5*(A1<>INT(A1))&","&1*(A1<>INT(A1))&","&TRUNC(A1/5)

```

Input is in cell `A1`.

Working backwards:
`TRUNC(A1/5)` gives the max number of 5mg pills by dividing and truncating.
`1*(A1<>INT(A1))` gives the 2.5mg pill count as `1` if the dose is decimal and `0` if it isn't.
`MOD(A1,5)-2.5*(A1<>INT(A1))` gives the 1mg pill count by taking whatever's left from dividing by 5 and subtracting 2.5 if the dose is a decimal.

# Answer
> 3 votes
# JavaScript (ES6), 31 bytes

Outputs an array in the order 5mg, 2.5mg, 1mg. Essentially the same logic as @RobinRyder.

```
v=>[x=v/5|0,v%1&&1,v-(v%1+x)*5]

```

Try it online!

---

# JavaScript (ES6), 27 bytes

A port of @ManishKundu's answer suggested by @KevinCruijssen.

```
v=>[v/5|0,v%1*2,(v<20)*v%5]

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~68~~ ~~64~~ ~~57~~ ~~51~~ ~~43~~ ~~38~~ ~~36~~ ~~34~~ 32 bytes

```
lambda x:[x//5,x%1*2,(x<20)*x%5]

```

Try it online!

Outputs in order (5, 2.5, 1).

Explanation: Uses as many 5 mg pills as possible, one pill of 2.5 mg if x % 5 = 2.5, otherwise none, and remaining sum is formed using 1 mg pills.

*-11 bytes thanks to Stef*

# Answer
> 3 votes
# 05AB1E, ~~14~~ ~~12~~ 11 bytes

```
5‰`D.ïD≠Š*)

```

Output is in the order `[5, 2.5, 1]`.

Try it online or verify all test cases.

**Explanation:**

```
5‰           # Divmod the (implicit) input by 5: [input//5, input%5]
  `          # Pop and push both values separated to the stack
   D         # Duplicate the input%5
    .ï       # Check if it's an integer (1 if truthy; 0 if falsey)
      D      # Duplicate that
       ≠     # Check that it's NOT equal to 1 (1 becomes 0; 0 becomes 1)
        Š    # Triple swap the top three values on the stack: a,b,c → c,a,b
         *   # Multiply the top two
          )  # Wrap all three values on the stack into a list
             # (after which it is output implicitly as result)

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 37 bytes

```
#&@@{2,5,10}~FrobeniusSolve~⌊2#⌋&

```

Try it online!

Unfortunately, `NumberDecompose[8,{10,5,2}]` is `{0,1,3/2}`, not `{0,0,4}`.

The documentation for `NumberDecompose` states that "For integers, `NumberDecompose` returns the last solution found by `FrobeniusSolve`", but this is evidently not the case. Try it online!

# Answer
> 2 votes
# Charcoal, 16 bytes

```
ＮθＩ⟦÷θ⁵﹪⊗θ²﹪×⁶θ⁵

```

Try it online! Port of @xnor's solution, saving 3 bytes over a generic solution such as a port of the other solutions. Explanation:

```
Ｎθ

```

Input the dose.

```
Ｉ⟦

```

Output the result on separate lines.

```
÷θ⁵

```

Integer divide the dose by 5.

```
﹪⊗θ²

```

Modulo the doubled dose by 2.

```
﹪×⁶θ⁵

```

Modulo the sextupled dose by 5.

# Answer
> 2 votes
# APL (Dyalog Unicode), 17 bytes

```
|⌊0 ¯1 5|.2 1 6×⎕

```

Try it online!

```
|∘⌊÷∘5,¯1∘|,5|6∘×

```

Try it online!

```
3↑0 1,⍨(⊢∩⌊)0 5⊤⎕

```

Try it online!

First two are the ports of xnor's Python answer giving `5mg 2.5mg 1mg`, and the last is from Jonathan Allan's Jelly answer giving `5mg 1mg 2.5mg`. The first and third are full programs, and the second is a tacit function.

### How all these work

```
|⌊0 ¯1 5|.2 1 6×⎕  ⍝ Input: single number x
         .2 1 6×⎕  ⍝ (x/5)(x)(6x)
  0 ¯1 5|          ⍝ (x/5)(x%-1)(6x%5); x%-1==-0.5 if x%1==0.5
|⌊                 ⍝ Floor then abs

|∘⌊÷∘5,¯1∘|,5|6∘×  ⍝ Input: single number x
            5|6∘×  ⍝ 6x%5
       ¯1∘|        ⍝ x%-1
   ÷∘5             ⍝ x/5
|∘⌊   ,    ,       ⍝ Concatenate all and floor then abs

3↑0 1,⍨(⊢∩⌊)0 5⊤⎕  ⍝ Input: single number x
            0 5⊤⎕  ⍝ (x//5)(x%5)
       (⊢∩⌊)       ⍝ Discard non-integers
  0 1,⍨            ⍝ Append two numbers 0 1
3↑                 ⍝ Take 3 from the head

```

# Answer
> 1 votes
# Pyth, 16 bytes

```
/Q5*2%Q1*%Q5<Q20

```

Try it online!

Same as my Python solution. Output contains 3 lines: number of 5 mg pills, 2.5 mg pills and 1 mg pills respectively.

# Answer
> 1 votes
# C (clang), ~~72~~ ~~69~~ 67 bytes

```
y;f(float x){printf("%d,%d,%d",(y=x*10)/50,y=y%50==25,!y*(y=x)%5);}

```

Try it online!

Saved 1 thanks to @ceilingcat

Saved 2 thanks to @rtpax

Output n#5mg, n#2.5, n#1

# Answer
> 1 votes
# Retina 0.8.2, 40 bytes

```
^\d+
$*
^(1{5})*(1)*(11.5)*$
$#1 $#3 $#2

```

Try it online! Link includes test suite. Explanation:

```
^\d+
$*

```

Convert the integer part of the dose to unary.

```
^(1{5})*(1)*(11.5)*$

```

Divmod by 5, then split the remainder into 1s and an optional 2.5 (if the original dose was not an integer).

```
$#1 $#3 $#2

```

Output the numbers of the pills in the order 5s, 2.5s, 1s.

# Answer
> 1 votes
# Arn, ~~12~~ 11 bytes

Based off of Manish Kundu's and xnor's answers. Gives `[1mg, 5mg, 2.5mg]`

```
ê═]²*►U¦█–)

```

Try it!

# Explained

Unpacked: `[*6%5:v/5:+%1`

```
[ Begin sequence of elements

  *6%5 Perform (_ times 6) mod 5

  :v/5 Floor _ divided by 5

  :+%1 Double _ mod 1

] End sequence, implied

```

Variable `_` is implied. Initialized to STDIN when a program begins.

# Answer
> 1 votes
# Perl 5 -pl, 32 bytes

```
$_=join' ',int$_/5,0+/\D/,$_*6%5

```

Try it online!

# Answer
> 1 votes
# T-SQL, 31 bytes

```
SELECT @%5-@%1*5,@%1*2,str(@)/5

```

**Try it online**

# Answer
> 1 votes
# Go, 104 bytes

```
import ."math"
func f(x float64)(int,float64,int){return int(x/5),Ceil(x)-Floor(x),int(Min(20/x,1)*x)%5}

```

Try it online!

---
Tags: code-golf
---


title: Generate valid Fibonacci tilings

text:
# Question
Title: Generate valid Fibonacci tilings
## Background

The Fibonacci tiling is a tiling of the (1D) line using two segments: a short one, *S*, and a long one, *L* (their length ratio is the golden ratio, but that's not relevant to this challenge). For a tiling using these two prototiles to actually be a Fibonacci tiling, the following conditions have to be fulfilled:

* The tiling must not contain the subsequence *SS*.
* The tiling must not contain the subsequence *LLL*.
* If a new tiling is composed by performing all of the following substitutions, the result must still be a Fibonacci tiling:
    1. *LL**S*
    2. *S**L*
    3. *L**(empty string)*

Let's look at some examples:

```
SLLSLLSLLSLS

```

This looks like a valid tiling, because it doesn't contain two \*S\*s or three \*L\*s but let's perform the composition:

```
LSLSLSLL

```

That still looks fine, but if we compose this again, we get

```
LLLS

```

which is not a valid Fibonacci tiling. Therefore, the two previous sequences weren't valid tilings either.

On the other hand, if we start with

```
LSLLSLSLLSLSLL

```

and repeatedly compose this to shorter sequences

```
LSLLSLLS
LSLSL
LL
S

```

all results are valid Fibonacci tilings, because we never obtain *SS* or *LLL* anywhere inside those strings.

For further reading, there is a thesis which uses this tiling as a simple 1D analogy to Penrose tilings.

## The Challenge

Write a program or function which, given a non-negative integer *N*, returns all valid Fibonacci tiling in the form of strings containing *N* characters (being `S` or `L`).

You may take input via function argument, STDIN or ARGV and return or print the result.

This is code golf, the shortest answer (in bytes) wins.

## Examples

```
N      Output
0      (an empty string)
1      S, L
2      SL, LS, LL
3      LSL, SLS, LLS, SLL
4      SLSL, SLLS, LSLS, LSLL, LLSL
5      LLSLL, LLSLS, LSLLS, LSLSL, SLLSL, SLSLL
...
8      LLSLLSLS, LLSLSLLS, LSLLSLLS, LSLLSLSL, LSLSLLSL, SLLSLLSL, SLLSLSLL, SLSLLSLL, SLSLLSLS

```

# Answer
> 4 votes
# CJam, ~~70~~ ~~62~~ 59 bytes

```
Qali{_'L:Xf+\'S:Yf++}*{{_X2*/Xf-Yf/Xf*Y*}h]N*_X3*#\Y2*#=},p

```

Reads from STDIN. Try it online.

### Example run

```
$ cjam tilings.cjam <<< 5
["LLSLL" "SLSLL" "SLLSL" "LSLSL" "LSLLS" "LLSLS"]

```

### How it works

The idea is to push all strings of L's and S's of the proper length, successively apply the transformation to each until the result is an empty string, concatenate the sequences of strings and search for the forbidden substrings.

```
Qa         " Push R := [ '' ].                                                            ";
li{        " Do the following int(input()) times:                                         ";
  _'L:Xf+  " Append (X := 'L') to a copy of all strings in R.                             ";
  \'S:Yf+  " Append (Y := 'S') to all original strings in R.                              ";
  +        " Concatenate the arrays into R.                                               ";
}*         " R now contains all strings of L's and S's of length int(input()).            ";
{          " For each S ∊ R:                                                              ";
  {        "                                                                              ";
    _      " Push a copy of S.                                                            ";
    X2*/   " Split S at 'LL'.                                                             ";
    Xf-    " Remove 'L' from the chunks.                                                  ";
    Yf/    " Split the chunks at 'S'.                                                     ";
    Xf*    " Join the chunks, separating by 'L'.                                          ";
    Y*     " Join, separating by 'S'.                                                     ";
  }h       " If the resulting string is non-empty, repeat.                                ";
  ]N*      " Join the array of resulting strings from S to '', separating by linefeeds.   ";
  _X3*#    " Push the index of 'LLL' a copy in the resulting string (-1 if not present).  ";
  \Y2*#    " Push the index of 'SS' in the original string (-1 if not present).           ";
  =        " Check if the indexes are equal; this happens if and only if both are -1.     ";
},         " Filter: Keep S in R if and only if = pushed 1.                               ";
p          " Print a string representation of R.                                          ";

```

# Answer
> 6 votes
# APL (Dyalog Unicode), 43 bytes

```
(1+∘÷⍣=1){'LS'[∪2</⍺|(⍺×(⍳÷⊢)2*⍵)∘.+⍳⍵]}1∘+

```

Try it online!

This uses the alternative formulation (actually the first one) shown in the linked paper: the closest integer staircase to the line \\$y = x/\phi\\$, where \\$\phi\\$ is the golden ratio \\$\frac{\sqrt5+1}{2}\\$.

Given the initial vertical offset from the line \\$h\\$ (which can be positive or negative), the next term (one of `LS`) can be determined by the following rule:

* If \\$h\<0\\$ (below the line), \\$h←h+1\\$ and emit `S`.
* Otherwise (over the line), \\$h←h-(\phi-1)\\$ and emit `L`.

Since \\$h-(\phi-1) = h+1-\phi\\$, we can always increment and take modulo \\$\phi\\$ of it. Then the condition \\$h\<0\\$ changes to \\$h\<\phi-1\\$, but it doesn't affect the resulting sequence of terms.

Then the problem becomes to sample enough values for initial \\$h\\$ so that we can get all possible sequences of `SL` for any given length \\$n\\$. I choose \\$2^{n+1}\\$ points uniformly spaced over the interval \\$\[0,\phi)\\$, which works for small \\$n\\$, and the gap size reduces faster than that induced by the collection of lines \\$y=x/\phi+c\\$, each passing through some lattice point inside \\$0 \le x \le n\\$.

Finally, I determine the actual `SL` terms by checking each consecutive pair: `S` if `left < right`, `L` otherwise, and take unique sequences.

```
(1+∘÷⍣=1){'LS'[∪2</⍺|(⍺×(⍳÷⊢)2*⍵)∘.+⍳⍵]}1∘+  ⍝ Input: n
(1+∘÷⍣=1){...}1∘+  ⍝ Pass n+1 and phi to the inner dfn...
⍳⍵            ⍝ Range 0..n
∘.+           ⍝ Outer product by addition...
(⍺×(⍳÷⊢)2*⍵)  ⍝ 2^(n+1) uniformly separated numbers in [0,phi)
⍺|            ⍝ Modulo phi
2</           ⍝ Pairwise comparison in row direction
              ⍝ (1 if right is higher, 0 otherwise)
∪             ⍝ Take unique rows
'LS'[...]     ⍝ Map 0, 1 to L, S

```

# Answer
> 3 votes
## GolfScript (86 bytes)

```
~:|'LS'1/\{{.{1&!'LLS'2/=}%'SS'/'SLS'*[.(1&{'LS'\+}*]{.)1&{'SL'+}*}/}%.&}*['']+{,|=},p

```

This is an inflationary approach: it starts with `L` and `S` and expands them using the rules `LL -> SLS`, `L -> S`, `S -> LL`, and leading or trailing `S` can have an `L` added at the word boundary.

Online demo

# Answer
> 2 votes
# Brachylog, 69 bytes

```
~{Ėl|l.&ċ∈ᵛ"LS"&~c=ᵐ{¬{s₂tʰhᵗ=}&}cᵐ{"LL"∧"S"|"S"∧"L"|"L"∧""}ᵐcẹ↰∧}ᵘcᵐ

```

Try it online!

### How it works

First define a predicate, that has a valid fibonacci tiling as input (as a list of `"L"` and `"S"`), and its length as output.

```
Ėl|

```

It's either an empty list `Ė`, returning it's length `l` or …

```
l.&ċ∈ᵛ"LS"

```

Something which length is the output and is a list which elements all are elements of `"LS"`. (This part was rather annoying for how simple it should be; I couldn't generate *strings* up to length `N` consisting of `"LS"`.)

```
&~c=ᵐ

```

Also, the input splitted in groups where each group has only one unique element, e.g. `[S, LL, S]` or `[S, L, L, S]` or `[LLLL]`

```
{¬{s₂tʰhᵗ=}&}

```

Has no two consecutive groups where the first group's last element and the second group's first element are the same – to filter out `[S, L, L, S]`. (Is there a way to drop `{…&}` here?)

```
cᵐ{"LL"∧"S"|"S"∧"L"|"L"∧""}ᵐcẹ↰∧

```

Those groups are then replaced. If a group doesn't match one of the three rules, the whole partition of the string gets thrown out, i.e. `[LLLL]` isn't valid. The replaced groups then, converted to a list, must also fulfill this predicate.

```
~{…}ᵘcᵐ

```

We now find all unique fibonacci tilings that have the length of the input and convert the lists back to strings.

# Answer
> 1 votes
Haskell, 217

```
import Control.Monad
data F=L|S deriving (Eq)
f n=filter s$replicateM n [L,S]
r (L:L:m)=S:r m
r (S:m)=L:r m
r (L:m)=r m
r []=[]
s []=True
s m|v m=s$r m
s _=False
v (L:L:L:_)=False
v (S:S:_)=False
v (_:m)=v m
v []=True

```

Explaination:

I define 4 functions:

* `f` takes an integer and returns the result

`replicateM n [L,S]` creates all possible permutations of `[L,S]` with the length `n` `filter s ...` will filter this list (of lists) with the function `s`
* `r` reduces a a given list by 1 level.

This is simply done by pattern matching. A list starting with 2 `L` will become a list starting with `S` and the reduced remaining
* `v` validates a given list by the rules given (no 3 continuous L, no 2 continous S)

if the list starts with one of the 2 illegal sequences (L,L,L or S,S) the result is `False`, an empty list is valid, and an non-empty list is checked again with the first element removed
* `s` checks if a list and all reduced lists are valid.

Again: an empty list is valid (and can't be reduced further).
If the list given as argument is valid then the list is reduced ad checked with `s` again.
Otherwise the result is `False`

---
Tags: code-golf, fibonacci, tiling
---


title: Print a Lego piece

text:
# Question
Title: Print a Lego piece
This challenge is a simple one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```
(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o

```

If you can't tell from the test-cases, the top and bottom are `width*2+3` underscores and dashes, and each row has pipes for the sides, `o`'s for the little things, and everything is separated by spaces.

The only exception for this is `(1, 1)`, which is just a single `o`.

You will never get `0` for any of the dimensions.

This is , so shortest code in **bytes** wins!

```
var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Befunge, 165 ~~227~~ bytes

```
&::&*:1` v
v+3*2:\/\_"o",@
v       _$ v<
>"_",1-:^  2
v:,,"| ",*5<
v         _v
>" o",,1-:^$
>*v>\     #\^
5 #|:-1,"|"<
^2$<
v1, *95<
- >2*3+^
>:    #^_@

```

Not as much whitespace as before, but there are still gaps. The principle is the same as in the previous solution, but the layout is different. This time, to check if both numbers are 1, I'm just taking their product and seeing if the result is greater than 1.

---

Old solution (227 bytes)

```
v           v       <
&   >>\:2*3+>"_",1-:|
>&:1`|v ,,"| ",*52:$<   :\<
    #\v         <
     :>" o",,1-:|
     1          >"|",$\1-:|
    \`            @       $
    ^_"o",@>:!    |       2
           ^-1,*95<+3*2,*5<

```

It might be possible to golf it more. Just look at all that whitespace!

Here's my poor attempt at an explanation in MSPaint picture form:  Code flows in the direction of the arrow.
> 53 votes

# Answer
# , ~~43, 40, 38~~ 36 bytes

One of the longest V answers I've ever written...

```
Àio ddÀPñóo î½o
u2Pí.«/| °|
Vr-HVr_

```

Try it online!

Since this contains unicode and unprintable characters, here is a reversible hexdump:

```
0000000: c069 6f20 1b64 64c0 50f1 f36f 20ee bd6f  .io .dd.P..o ..o
0000010: 0d0a 7532 50ed 2eab 2f7c 20b0 7c0d 0a56  ..u2P.../| .|..V
0000020: 722d 4856 725f                           r-HVr_

```

This challenge is about manipulating text, so perfect for V! On the other hand, V is terrible at conditionals and math, so the differing output for (1, 1) really screwed it up... :(

Explanation:

```
À                   "Arg1 times:
 io <esc>           "Insert 'o '
         dd         "Delete this line, and
           À        "Arg2 times:
            P       "Paste it

```

Now we have 'Height' lines of o's with spaces between them.

```
ñ                   "Wrap all of the next lines in a macro. This makes it so that if any
                    "Search fails, execution will stop (to handle for the [1, 1] case)
 ó                  "Search and replace
  o î½o             "'o'+space+0 or 1 newlines+another 'o'

u                   "Undo this last search/replace
 2P                 "Paste twice
   í                "Search and replace on every line
    .«/| °|         "A compressed regex. This surrounds every non-empty line with bars.

Vr-                 "Replace the current (last) line with '-'
   H                "Move to line one
    Vr_             "Replace this line with '_'

```

Non-competing version (31 bytes):

Try it online!

This version uses several features that are newer then this challenge to be 5 bytes shorter!

Second explanation:

```
ddÀP

```

which is "Delete line, and paste it *n* times" is replaced with `ÀÄ` which is "Repeat this line *n* times". (-2 bytes)

```
óo î½o
u

```

which was "Replace the first match of this regex; Undo" was replaced with

```
/o î½o

```

Which is just "Search for a match of this regex" (-1 byte)

And lastly, `Ò` is just a simple synonym for `Vr`, which both "Replace every character on this line with 'x'". (-2 bytes)
> 25 votes

# Answer
# 32 16-bit little-endian x86 machine code, 57 54 51 bytes

*3 bytes less thanks to @ninjalj.*

*Heavily rewrote the code and have managed to shave off another 3 bytes*

In hex

```
FCBA6F208D48FFE20492AAEB2389D941D1E14151B05FF3AAEB0BB87C20AB89D992F3AB92AAB00AAA4E7DEF59B02DF3AA91AAC3

```

Input: BX=width, SI=height, DI points to the buffer that receives result as a NULL-terminated string with lines separated by "\n"

## Disassembly:

```
fc            cld
ba 6f 20      mov    dx,0x206f      ;Storing ' o' in DX for later use
8d 48 ff      lea    cx,[bx+si-0x1] ;CX=width+height-1
e2 04         loop   _main0         ;--CX & brahch if not zero
92            xchg   dx,ax          ;(1,1) case, swap DX & AX
aa            stosb                 ;AL == 'o', CX == 0
eb 23         jmp    _end
_main0:
89 d9         mov    cx,bx
41            inc    cx
d1 e1         shl    cx,1
41            inc    cx           ;Calculate (width+1)*2+1
51            push   cx           ;and save it for future use
b0 5f         mov    al,0x5f      ;'_'
f3 aa         rep    stosb        ;Output the whole line of them
eb 0b         jmp    _loopstart   ;Jump into the loop
_loop:
b8 7c 20      mov    ax,0x207c    ;' |'
ab            stosw               ;Output it once (left bar + space)
89 d9         mov    cx,bx        ;Copy width
92            xchg   dx,ax        ;AX == ' o'
f3 ab         rep    stosw        ;Output it CX times
92            xchg   dx,ax        ;Swap values back, AL == '|'
aa            stosb               ;Output only the right bar
_loopstart:
b0 0a         mov    al,0x0a      ;Newline. Can be replaced with mov ax,0x0a0d for windows newline
aa            stosb               ;convention (at the cost of 1 byte), with stosb replaced with stosw
4e            dec    si           ;Height--
7d ef         jge    _loop        ;Continue if si >= 0 (this accounts for the dummy first pass)
59            pop    cx
b0 2d         mov    al,0x2d      ;'-'
f3 aa         rep    stosb        ;Output bottom line
_end:
91            xchg   cx,ax        ;CX == 0, so swap to get zero in AL
aa            stosb               ;NULL-terminate output
c3            retn

```
> 22 votes

# Answer
## Python 2, ~~75~~ ~~73~~ 72 bytes

```
lambda x,y:(x*'__'+'___\n'+('| '+'o '*x+'|\n')*y+'-'*(x*2+3),'o')[x<2>y]

```

Returns a string, with a conditional to handle the 1,1 block.

*Thanks to Lynn and Chepner for two bytes*
> 20 votes

# Answer
# CJam, 34

```
'_q~'o*"||"\*S*f*f+'-f+zN*_,H='o@?

```

Try it online

**Explanation:**

```
'_        push a '_' character
q~        read and evaluate the input (height and width)
'o*       repeat the 'o' character <width> times
"||"\*    join the "||" string by the string of o's (putting them in between)
S*        join with spaces (inserting a space between every 2 characters)
f*        repeat each character <height> times, making it a separate string
f+        prepend '_' to each string
'-f+      append '-' to each string
z         transpose the array of strings
N*        join with newlines; lego piece is ready, special case to follow
_,        duplicate the string and get its length
H=        compare with H=17
'o        push 'o' for the true case
@         bring the lego piece to the top for the false case
?         if the length was 17, use 'o' else use the lego piece

```
> 13 votes

# Answer
# Ruby, ~~59~~ 56 bytes

Anonymous function, returns a multiline string. Try it online!

-3 bytes thanks to borrowing a trick from @El'endiaStarman

```
->w,h{w*h<2??o:?_*(x=2*w+3)+$/+(?|+' o'*w+" |
")*h+?-*x}

```
> 11 votes

# Answer
# Java, 318 312 297 294 260 258 bytes

Saved 15 bytes thanks to cliffroot!

```
interface a{static void main(String[]A){int b=Byte.valueOf(A[0]),B=Byte.valueOf(A[1]),C=3+b*2;String c="";if(b<2&B<2)c="o";else{for(;C-->0;)c+="_";for(;B-->0;){c+="\n|";for(C=b;C-->0;)c+=" o";c+=" |";}c+="\n";for(C=3+b*2;C-->0;)c+="-";}System.out.print(c);}}

```

It works with command line arguments.

Ungolfed In a human-readable form:

```
interface a {
    static void main(String[] A) {
        int b = Byte.valueOf(A[0]),
            B = Byte.valueOf(A[1]),
            C = 3 + b*2;
        String c = "";
        if (b < 2 & B < 2)
            c = "o";
        else {
            for (; C-- > 0;)
                c += "_";
            for (; B-- > 0;) {
                c += "\n|";
                for (C = b; C-- >0;)
                    c += " o";
                c += " |";
            }
            c += "\n";
            for(C = 3 + b*2; C-- >0;)
                c += "-";
        }
        System.out.print(c);
    }
}

```

---

Yes, it's still difficult to understand what's going on even when the program is ungolfed. So here goes a step-by-step explanation:

```
static void main(String[] A)

```

The first two command line arguments -which we'll use to get dimensions- can be used in the program as `A[0]` and `A[1]` (respectively).

```
int b = Byte.valueOf(A[0]),
    B = Byte.valueOf(A[1]),
    C = 3 + b*2;
String c = "";

```

`b` is the number of columns, `B` is the number of rows and `C` is a variable dedicated for use in `for` loops.

`c` is the Lego piece. We'll append rows to it and then print it at the end.

```
if (b < 2 & B < 2)
    c = "o";
else {

```

If the piece to be printed is 1x1, then both `b` (number of columns) and `B` (number of rows) should be smaller than 2. So we simply set `c` to a single `o` and then skip **to** the statement that `System.out.print`s the piece if that's the case.

```
for (; C-- > 0; C)
    c += "_";

```

Here, we append `(integerValueOfA[0] * 2) + 3` underscores to `c`. This is the topmost row above all holes.

```
for (; B > 0; B--) {
    c += "\n|";
    for(C = b; C-- > 0;)
        c+=" o";
    c += " |";
}

```

This is the loop where we construct the piece one row at a time. What's going on inside is impossible to explain without examples. Let's say that the piece is 4x4:

```
Before entering the loop, c looks like this:
___________

After the first iteration (\n denotes a line feed):
___________\n
| o o o o |

After the second iteration:
___________\n
| o o o o |\n
| o o o o |

After the third iteration:
___________\n
| o o o o |\n
| o o o o |\n
| o o o o |

```

.

```
c += "\n";
for (C = 3 + b*2; C-- > 0;)
    c += "-";

```

Here, we append `(integerValueOfA[0] * 2) + 3` hyphens to the piece. This is the row at the very bottom, below all holes.

The 4x4 piece I used for explaining the `for` loop where the piece is actually constructed now looks like this:

```
___________\n
| o o o o |\n
| o o o o |\n
| o o o o |\n
| o o o o |\n
-----------

```

```
System.out.print(c);

```

And finally, we print the piece!
> 11 votes

# Answer
## Minkolang 0.15, ~~58~~ ~~57~~ 56 bytes

Yes, that's right. I golfed off *~~one~~ two stinkin' little bytes*...

```
nn$d*1-5&"o"O.rd2*3+$z1$([" o"]" ||"2Rlkr$Dlz["-_"0G]$O.

```

Try it here!

### Explanation

```
nn                Take two numbers from input (stack is now [w h])

                  C special case C
  $d              Duplicate stack
    *1-           Multiply and subtract 1
       5&         Jump 5 spaces if truthy
         "o"O.    Top of stack was 1*1-1=0, so output "o" and stop.

                     C precalculates width of top and bottom lines for later use C
         r           Reverse stack (now [h w])
          d          Duplicate top of stack
           2*3+      Multiply top of stack by 2 and add 3
               $z    Pop this and store in register (z = 2*w+3)

                                       C generates the row C
                 1$(                   Open while loop prepopulated with top of stack
                    [" o"]             w times, push "o "
                          " ||"        Push "|| "
                               2R      Rotate twice to the right
                                 l     Push newline (10)
                                  k    Break out of while loop

                                           C duplicates the row h times C
                                   r       Reverse stack
                                    $D     Duplicate whole stack h times
                                      l    Push newline

                     C this is for the top and bottom lines C
        z[           Open for loop that repeats z times
          "-_"       Push "_-"
              0G     Relocate top of stack to bottom of stack
                ]    Close for loop

                 $O.    Output whole stack as characters and stop.

```

Okay, that's two significant rewrites of the explanation for two bytes saved. I don't think I can or will golf anything more out of this one. :P
> 9 votes

# Answer
# brainfuck, 391 bytes

I know this can be golfed down more, but at this point I'm just glad it works. I will continue to work to golf it down.

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

```

Input needs to be given as just two digits. As in, to do `(8, 2)` you would just enter `82`.

Try it online!

**Breakdown:**

First put the necessary characters into the tape: `(newline)| o_-`

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

```

Then collect the input into two cells and subtract 48 from each (to get the numeric value and not the numeral character)

```
>,<,>>++++++[<--------<-------->>-]<<

```

Next, check for the special case of `(1, 1)` (Note that just this check accounts for 109 bytes of the code). As if `if`s weren't hard enough to do in brainfuck, we have a nested `if`:

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

```

The following is the structure to check if a cell x is zero or nonzero:

```
temp0[-]+
temp1[-]
x[
 code1
 temp0-
 x[temp1+x-]
]
temp1[x+temp1-]
temp0[
 code2
temp0-]

```

However in a nested `if`, we need to have 4 temporary cells.

Now we get to the actual printing of characters:

Print the top bar and a newline:

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

```

Print a `|`, a row of `o`'s, another `|` and a newline a number of times equal to the height:

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

```

And print the bottom bar (no newline needed here):

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

```
> 8 votes

# Answer
# Jolf, 36 bytes

```
?w*jJρΡ,a+3ώj+2J'-"-+"d*'_lH"  ' o'o
?w*jJ                             'o   return "o" if j * J - 1
       ,a                              make a box
         +3ώj                           of width +3ώj = 3+2*j
             +2J                        of height +2J = 2+J
                '-                      specifying corners as "-"
      Ρ           "-+"                 replacing the first run of "-"s
                      d*'_lH            with a run of "_"s of equal length
     ρ                      "  '       replacing all "  "
                               ' o      with " o"

```

# Jolf, 24 bytes, noncompeting

Well, I made a better box builtin.

```
?w*jJ,AhώjJ"_-'_-'|' o'o

```

# Jolf, ~~38~~ 37 bytes

```
?w*jJΆ+*'_γ+3ώjS*JΆ'|*j" o' |
"*'-γ'o

```

Simple stuff, really. Saved a byte by noting that  (math zeta, or the stand deviance) is only 0 when both arguments are 1, and is falsey otherwise (for our case).
> 7 votes

# Answer
## Retina, 52 bytes

Byte count assumes ISO 8859-1 encoding. Note that the sixth line is supposed to contain a single space.

```
\G1?
$_¶
1*

.+
|$&|
\G.
_
r`.\G
-
s`^.{17}$|1
o

```

Try it online!

Input is in unary, using `1` as the unary digit, space as a separator and height followed by width.

### Explanation

All stages in this program are bare substitutions, occasionally with a regular regex modifier (no repetition or loops, no other types of stages). It doesn't even use Retina-specific substitution features, apart from the usual  alias for linefeeds.

```
\G1?
$_¶

```

The purpose of this is to "multiply" the two inputs. Our goal is to create `h+2` rows with `w` `1`s each (`h+2` so that we can turn the top and bottom into `_` and `-` later). The `\G` anchor requires the match to start where the last one left off. That is, if we ever fail to match a character in the string, further characters won't match either. We use this to match only the `1`s in `h`, but not in `w` because the regex doesn't allow the space that separates them to be matched. However, we also make the `1` optional, so that we get an additional empty match at the end of `h`. That's `h+1` matches. Each of those is replaced with the entire input (`$_`) followed by a linefeed. `w` itself remains untouched which gives us the `h+2`nd copy. Say the input was `11 1111`, then we've now got:

```
11 1111
11 1111
11 1111
 1111

```

That's pretty good. We've got some extra stuff, but the `h+2` copies of `w` are there.

```
1*

```

Note that there's a space at the end of the first line. This removes those prefixes from the lines so that we only have the `w`s afterwards.

```

```

Ah well, that doesn't really work with SE's formatting... the first line is empty and the second line is supposed to contain a single space. This inserts spaces into every possible position, i.e. at the beginning and end of each line and between every pair of `1`s:

```
 1 1 1 1
 1 1 1 1
 1 1 1 1
 1 1 1 1

```

We will turn these into `o`s later

```
.+
|$&|

```

This simply wraps every line in a pair of `|`:

```
| 1 1 1 1 |
| 1 1 1 1 |
| 1 1 1 1 |
| 1 1 1 1 |

```

Now we take care of the top and bottom:

```
\G.
_

```

Time for `\G` to shine again. This matches each character on the first line and turns it into a `_`.

```
r`.\G
-

```

Same thing, but due to the `r` modifier (right-to-left mode), this matches the characters on the *last* line and turns them into `-`. So now we've got:

```
___________
| 1 1 1 1 |
| 1 1 1 1 |
-----------

```

There's only two things left to do now: turn those `1` into `o`s, and if the input was `1 1` then turn the entire thing into `o` instead. We can handle both of those with a single stage:

```
s`^.{17}$|1
o

```

`s` is regular singleline mode (i.e. it makes `.` match linefeeds). If the input was `1 1` the result will have the minimum size of 17 characters so we can match it with `^.{17}$` and replace it with `o`. Otherwise, if that fails, we'll just match all the `1`s and replace those with `o` instead.
> 7 votes

# Answer
## JavaScript (ES6), ~~89~~ 86 bytes

```
(x,y,g=c=>c[r=`repeat`](x*2+3))=>x*y-1?g(`_`)+`
`+`| ${`o `[r](x)}|
`[r](y)+g(`-`):`o`

```

Edit: Saved 3 bytes thanks to @Shaggy.
> 6 votes

# Answer
# 05AB1E, 33 bytes

Code:

```
*i'oë¹·3+©'_×¶²F'|„ o¹×„ |¶}®'-×J

```

Explanation:

```
*i'o                               # If both input equal 1, push "o"
    ë                              # Else, do...
     ¹·3+                          # Push input_1 × 2 + 3
         ©                         # Copy this number to the register
          '_×                      # Multiply by "_"
             ¶                     # Push a newline character
              ²F           }       # Do the following input_2 times:
                '|                 # Push "|"
                  „ o              # Push " o"
                     ¹×            # Multiply this by input_1
                       „ |         # Push " |"
                          ¶        # Push a newline character
                            ®      # Retrieve the value from the register
                             '-×   # Multiply by "-"
                                J  # Join everything and implicitly print.

```

Uses the **CP-1252** encoding. Try it online!.
> 6 votes

# Answer
# Python 2, 71 bytes

```
lambda x,y:('o',x*'__'+'___\n'+'| %s|\n'%('o '*x)*y+'-'*(x*2+3))[x+y>2]

```
> 5 votes

# Answer
# Befunge, 144 Bytes

I would have prefered to comment to this post, but I don't have the reputation yet, so I'm putting an answer of my own, which works a similar way, but is slightly more compact

```
&::&*:1`v
v3*2:\/\_"o",@
>+:  v   >52*," |",, v
>,1-:vLEG O MAKERv::\<
^"_" _$\:|<v "o "_v
v52:+3*2$<,>,,1-:^$
>*,v <    ^"|":-1\<
v-1_@,
>:"-"^

```

you can test the code here
> 5 votes

# Answer
# Reng v.4, 82 bytes, noncompeting

I pushed a bug fix that fixes functions being overwritten by themselves (please don't ask; my stuff is haunted)

```
i#wi#hhw+2e1+ø ~*x}o:{"-"ö<
"_"{:o}w2*3+#xx*2ø
"o"o~
ö"|"o"o"{Wo:o}w*"| "ooh1-?^#h

```

Takes input as space-joined numbers, like `4 2`. Try it here!
> 4 votes

# Answer
## Bash, 186,163,156, 148,131, 130 Bytes

```
 ## Arg1 - Lego width
 ## Arg2 - Lego height
function print_lego() {
(($1+$2>2))&&{
printf _%.0s `seq -1 $1`
echo
for((i=$2;i--;)){
 printf \|
 for((j=$1;j--;)){
  printf o
 }
 echo \|
}
printf =%.0s `seq -1 $1`
echo
}||echo o
}

```

Note: If you really need the lego to have hyphens for the last line, then change the last printf to

```
printf -- -%.0s `seq -1 $1`

```

and add two bytes.
> 4 votes

# Answer
## PowerShell v2+, 76 bytes

```
param($x,$y)if($x+$y-2){"_"*($z=$x*2+3);"|$(" o"*$x) |`n"*$y+'-'*$z;exit}"o"

```

Takes input, then checks an `if` statement. Since non-zero values are *truthy* in PowerShell, so long as at least one of `$x` and `$y` are not equal to `1`, the `if` will be true.

Inside the `if`, there's a series of string multiplications. First, we construct our string of underscores, saving `$z` for later. That gets placed on the pipeline. Next we construct our string of sides and pegs (with the pegs multiplied by `$x`), done `$y` times, and concatenate that with our dashes `$z` times. That string is then placed on the pipeline and we `exit`. The pipeline is flushed and printing is implicit. Note that we get the newline between the underscores and the first row of pegs for free, since the default `.ToString()` separator for array output is ``n` (and we're outputting an array of strings).

If the `if` is false, we're in the special `1 1` case, so we just put `"o"` by itself on the pipeline and exit, with printing again implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> .\print-a-lego-piece.ps1 1 1
o

PS C:\Tools\Scripts\golfing> .\print-a-lego-piece.ps1 5 3
_____________
| o o o o o |
| o o o o o |
| o o o o o |
-------------

```
> 4 votes

# Answer
# Perl 5 - 84 77 bytes

84 Bytes

```
sub l{($x,$y)=@_;$w=3+2*$x;warn$x*$y<2?"o":'_'x$w.$/.('| '.'o 'x$x."|\n")x$y.'-'x$w}

```

77 Bytes. With some help from Dom Hastings

```
sub l{($x,$y)=@_;$x*$y<2?o:'_'x($w=3+2*$x).('
| '.'o 'x$x."|")x$y.$/.'-'x$w}

```
> 4 votes

# Answer
## Batch, ~~172~~ 170 bytes

```
@echo off
if "%*"=="1 1" echo o&exit/b
set o=
for /l %%i in (1,1,%1)do call set o=%%o%% o
echo ---%o: o=--%
for /l %%i in (1,1,%2)do echo ^|%o% ^|
echo ---%o: o=--%

```

Edit: Saved 2 bytes thanks to ~~@CᴏɴᴏʀO'Bʀɪᴇɴ~~ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

I can save 7 bytes if I can assume delayed expansion is enabled.
> 3 votes

# Answer
## C, ~~202~~ 191 bytes

```
#define p printf
i,w,h;t(char*c){for(i=0;p(c),++i<w*2+3;);p("\n");}f(){t("_");for(i=0;i<w*h;)i%w<1?p("| o "):p("o "),i++%w>w-2&&p("|\n");t("-");}main(){scanf("%d %d",&w,&h);w*h<2?p("o"):f();}

```

Thanks to @Lince Assassino for saving 11 bytes!

Ungolfed:

```
#include <stdio.h>
#define p printf

int i, w, h;

void t(char *c)
{
    for(i=0; p(c), ++i<w*2+3;);
    p("\n");
}

void f()
{
    t("_");
    for(i=0; i<w*h;)
    {
        i%w<1 ? p("| o ") : p("o ");
        i++%w>w-2 && p("|\n");
    }
    t("-");
}

int main()
{
    scanf("%d %d", &w, &h);
    w*h<2 ? p("o") : f();
}

```
> 3 votes

# Answer
# Vim, 56 keystrokes

This seems like a text editing task, so Vim is the obvious choice! I take input as a text file with two space separated integers and output the answer into the same file. Also, I hate you for having the 1x1 special case... Anyway:

```
"adt l"bDro:if@a*@b==1|wq|en<cr>Di| |<esc>@aio <esc>yy@bPVr_GpVr-ZZ

```

and if there hadn't been for the special case, 35 keystrokes

```
"adt x"bDi| |<esc>@aio <esc>yy@bPVr_GpVr-ZZ

```

## A breakdown for sane people:

```
"adt l"bD

```

Delete numbers from buffer into @a and @b (space char kept)

```
         ro:if@a*@b==1|wq|en<cr>

```

Replace space with "o" and if special case, save and quit

```
                                Di| |<esc>

```

Clear the line and write the edges of the lego block

```
                                          @aio <esc>

```

Insert @a lots of "o " to get a finished middle part

```
                                                    yy@bP

```

Yank line and make @b extra copies (one too many)

```
                                                         Vr_

```

We are at top of buffer, replace extra line with underscores

```
                                                            Gp

```

Jump to bottom of buffer, pull line that we yanked earlier

```
                                                              Vr-ZZ

```

Replace line with dashes, save and quit
> 3 votes

# Answer
# Cinnamon Gum, 32 bytes

```
0000000: 6c07 d5f5 7a5d 9cdf 5ae6 52ae 4050 0c35  l...z]..Z.R.@P.5
0000010: 18d9 052f 0082 9b42 e7c8 e422 5fe4 7d9f  .../...B..."_.}.

```

Non-competing. Try it online. Input must be exactly in the form `[width,height]` with no space in between the comma and the height.

# Explanation

The string decompresses to this:

```
l[1,1]&o;?&`p___~__~
%| ~o ~|
%---~--~

```

The first `l` stage maps `[1,1]` to `o` (the special case) and everything else to the string

```
`p___~__~
%| ~o ~|
%---~--~

```

The backtick then signals the start of a second stage; instead of outputting that string, CG chops off the backtick and executes the string. The `p` mode then repeats all the characters inside the tildes first parameter (width) times and then afterwards repeats the characters inside the percent signs second parameter (height) times. So for `[4,2]` it turns into this:

```
___________
%| o o o o |
%-----------

```

and then into:

```
___________
| o o o o |
| o o o o |
-----------

```
> 3 votes

# Answer
# Befunge, ~~114~~ ~~113~~ ~~108~~ 101 bytes

I know there are already a number of Befunge solutions, but I was fairly certain they could be improved upon by taking a different approach to the layout of the code. I suspect this answer can be golfed further as well, but it is already a fair bit smaller than either of the previous entries.

```
&::&+:2`^|,+55_"_",^
-4:,,"| "<\_|#:+1\,,"|"+55$_2#$-#$" o",#!,#:<
  ,"-"_@#:-1<
 :*2+2\-_"o",@v!:-1<

```

Try it online!
> 3 votes

# Answer
# Pyth, 38 bytes

```
?t*QJEjb+sm\_K+\|+j\o*dhQ\|+mKJsm\-K\o

```

Test suite.
> 2 votes

# Answer
# Haskell, 76 bytes

```
1#1="o"
w#h|f<-w*2+3=f!"_"++'\n':h!('|':w!" o"++" |\n")++f!"-"
n!s=[1..n]>>s

```

Usage example: `3 # 2` gives you a multiline string for a 3-by-2 brick.

Ungolfed:

```
(#) :: Int -> Int -> String
1     #   1    = "o"
width # height = let longWidth = 2 * width + 3 in -- golfed as 'f'
                      (        longWidth `times` "_"  ++   "\n" )
  ++ height   `times` ( "|" ++     width `times` " o" ++ " |\n" )
  ++                  (        longWidth `times` "-"            )

-- | golfed as (!)
times :: Int -> [a] -> [a]
times n s = concat $ replicate n s

```
> 2 votes

# Answer
# Groovy, 107, 98, 70, 64

```
{x,y->t=x*2+3;x<2&&y<2?"o":'_'*t+"\n"+"|${' o'*x} |\n"*y+'-'*t}

```

Testing:

```
(2,2)
(1,1)
(8,2)
(1,4)
_______
| o o |
| o o |
-------
o
___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------
_____
| o |
| o |
| o |
| o |
-----

```
> 2 votes

# Answer
# PHP 7, 98 bytes

```
<?=($P=str_pad)("",$w=3+2*$argv[1],_).$P("",$argv[2]*++$w,$P("
| ",$w-1,"o ")."|").$P("
",$w,"-");

```

`str_pad` saves a little from `str_repeat`.
Juggling with preincrement on `$w` saves two bytes.
But version 7 is needed for assigning `$r` while using it at the same time.
> 2 votes

# Answer
## Octave, ~~97~~ ~~95~~ 86 bytes

```
@(w,h){[a=~(1:w*2+3)+95;repmat(['| ' repmat('o ',1,w) '|'],h,1);~a+45],'o'}{(w*h<2)+1}

```

I used the @atlasologist's method in Python to test `(1, 1)`: `(...,'o')[x<2>y]`

Thanks to @Luis Mendo for saving 7 bytes: `a=ones(1,w*2+3)*'_'` to `a=~(1:w*2+3)+95` and `a./a*'-'` to `~a+45`

Thanks to @pajonk for saving 2 bytes: ~~`f=`~~
> 1 votes

# Answer
## APL, 46 bytes

```
{⍵≡1 1:'o'⋄'-'⍪⍨'_'⍪'|',' ','|',⍨'o '⍴⍨1 2×⌽⍵}

```

The guard: `⍵≡1 1:'o'` for the special case. Otherwise `'o '⍴⍨1 2×⌽⍵` builds the content. And the rest is just the boxing.
> 1 votes

# Answer
# Retina, ~~112~~ 111 bytes

Makes the piece the correct width, then adds rows. Performs a substitution at the end if the result was a 1x1. Takes input like `4,2`. Byte count assumes ISO 8859-1 encoding.

```
\d+
$*
1$
¶___¶| |¶---
+s`1(,.*)(¶.* )(.*)
$1__$2o $3--
+sm`1(.*)(^.*$¶)(.*)
$1$2$2$3
,¶

_____¶\| o \|¶-----
o

```

**Try it online**

### Fun fact:

You can give multiple inputs on separate lines and it will add them together into a single LEGO!
> 1 votes

# Answer
## C#, 198 bytes

```
void f(int x,int y){int l=x*2+3;Console.Write(y==x&&x==1?"o":s("_",l)+"\n"+s("|"+s(" o",x)+" |\n",y)+s("-",l));}string s(string m,int u){return string.Join("",new string[u].Select(n=>m).ToArray());}

```

quick and dirty

I had to write a function that multiplies strings

ungolfed (for suggestions)

```
public static void f(int x,int y)
{
    int l=x*2+3;
    Console.Write(y == x && x == 1 ? "o" : s("_",l)+"\n"+ s("|" + s(" o", x) + " |\n", y) + s("-",l));

}
public static string s(string m,int u)
{
    return string.Join("", new string[u].Select(n => m).ToArray());
}

```
> 1 votes

# Answer
**J, 59 bytes.**

```
' o|_='&({~)@:((4,~3,2(,~"1)2 0,"1(1 0&($~)@,+:))^:(0===]))

```
> 1 votes

# Answer
## Common Lisp, 286 bytes

```
(let((columns(read))(rows(read)))(when(and(= columns 1)(= rows 1))(progn(write-char #\o)(exit)))(dotimes(i(+(* columns 2)3))(write-char #\_))(terpri)(dotimes(i rows)(format t "| ")(dotimes(i columns)(format t "o "))(format t "| ")(terpri))(dotimes(i(+(* columns 2)3))(write-char #\-)))

```
> 1 votes

# Answer
# PHP 4.1, 103 bytes

This is based on my answer on https://codegolf.stackexchange.com/a/57883/14732, which was where all the heavy lifting was done.

```
<?$R=str_repeat;printf($W+$H<3?o:"_%'_".($Z=1+$W*2)."s_
%s-%1$'-{$Z}s-",'',$R('|'.$R(' o',$W).' |
',$H));

```

This answer requires that `short_open_tags` and `register_globals` are enabled (which it is enabled by default).

You can pass the values using the keys `W` and `H`, over `POST`, `GET`, `SESSION` and `COOKIE`.

This outputs warnings to STDERR, which aren't errors. According to https://codegolf.meta.stackexchange.com/a/1655/14732, this is acceptable as long as it isn't disallowed in the question.
Removing the warnings costs me 2 bytes.
> 1 votes

# Answer
## Racket 174 bytes

```
(λ(w h)(let((dl(λ(s)(displayln s)))(d(λ(s)(display s))))(for((x(+ 3(* w 2))))(d"_"))
(dl"")(for((x h))(d"| ")(for((y w))(d"o "))(d"|")(dl""))(for((x(+ 3(* w 2))))(d"-"))))

```

Ungolfed:

```
(define (f1 w h)
    (let ((dl (λ (s) (displayln s)))
          (d (λ (s) (display s))))
      (for ((x (+ 3 (* w 2))))
        (d "_"))
      (dl "")
      (for ((x h))
        (d "| ")
        (for ((y w))
          (d "o "))
        (d "|")
        (dl ""))
      (for ((x (+ 3 (* w 2))))
        (d "-"))))

```

Testing:

```
(f 5 2)

```

Output:

```
_____________
| o o o o o |
| o o o o o |
-------------

```
> 1 votes

# Answer
# Charcoal, 41 bytes

```
¿⁼η⁼θ¹o≔⁺³×θ²κＵＲκ⁺²ηＰ×κ_Ｍ⁺η¹↓Ｐκ↗Ｆη«Ｐ×θ o↑

```

Draws a box to get the vertical sides, then manually draws the top and bottom.

Then, prints the o's line by line.

Link is to verbose version of code.

Try it online!
> 1 votes

# Answer
# JavaScript ES6, ~~134~~ 124 Bytes

```
function p(e,n){r='repeat';e*n-1?x="_"[r](2*e+3)+"\n"+("|"+" o"[r](e)+" |\n")[r](n)+"-"[r](2*e+3)+"\n":x="o",console.log(x)}

```
> 0 votes

# Answer
# SpecBAS - 87 bytes

```
1 INPUT w,h: x=w*2+3: ?IIF$(w=1 AND h=1,"o","_"*x+#13+(("| "+("o "*w)+"|"#13)*h)+"-"*x)

```

Uses an inline-IF to either print single "o" when width and height are 1, otherwise builds up a string. `#13` is the line feed character.
> 0 votes

# Answer
# Scala, 90 bytes

```
(w:Int,h:Int)=>{val A=2*w+3;if(w*h==1)"o"else s"${"_"*A}\n${s"| ${"o "*w}|\n"*h}${"-"*A}"}

```

paste the above function into your Scala REPL, and then invoke the function with the width and height arguments.
> 0 votes

# Answer
# JavaScript ECMAScript6 (92 94 91 87 Bytes)

92 Characters

`a=(w,h,r='repeat')=>w-h?"__"[r](w)+"__\n"+("|"+" o"[r](w)+" |\n")[r](h)+"--"[r](w)+"---":"o"`

## Everything below here is Correct

94 Characters

`a=(w,h,r='repeat')=>w*h-1?"__"[r](w)+"__\n"+("|"+" o"[r](w)+" |\n")[r](h)+"--"[r](w)+"---":"o"`

91 Characters

`a=(w,h)=>w*h-1?`${"__"[r='repeat'](w)}__\n`+('|'+" o"[r](w)+' |\n')[r](h)+"-"[r](w*2+3):"o"`

87 Characters (Smallest so Far)

```
a=(w,h)=>w*h-1?'__'[r='repeat'](w)+`__
`+('|'+' o'[r](w)+` |
`)[r](h)+'-'[r](w*2+3):'o'

```

I took what I learned from the other JavaScript Submissions and made it a lot smaller by writing mine from scratch and then working my way down, turns out you don't need any console.log or alert as by default it will push it to the console when there is an output

I am still working on it to see if I can make it smaller yet
> 0 votes

# Answer
# Swift, 182 Bytes

```
func p(w:Int,h:Int){let i=w*2+3;var s="";if w+h<3{s="o"}else{for _ in 0..<i{s+="_"};for _ in 0..<h{s+="\n|";for _ in 0..<w{s+=" o"};s+=" |"};s+="\n";for _ in 0..<i{s+="-"}};print(s)}

```

If this was a closure implementation the `func p(w:Int,h:Int)` could be deleted and `w` replaced with `$0` and `h` replaced with `$1` but then it would be only the implementation not the interface so I felt that was cheating...

## 2nd attempt 180 Bytes

```
func q(w:Int,h:Int){let l=w*2+3;var s="",a="";if w+h<3{s="o"}else{for _ in 0..<l{s+="_";a+="-"};for x in 0..<h*w{s+=x%h==0 ? "\n| o":x%h==w-1 ? " o |":" o"};s+="\n";s+=a};print(s)}

```

Improved using ternaries. Only 2 bytes though...

## 3rd attempt 263 bytes

```
func r(w:Int,h:Int){let l=w*2+3;var s="";if w+h<3{s="o"}else{for a in 0..<(h+2)*l{if a<l{s+="_";continue};if a>=(h+2)*l-l{s+=a%l==0 ? "\n-":"-";continue};let v=a%l>0&&a%l<l-2;s+=a%l==0 ? "\n|":v&&(a%l)%2==0 ? "o":v&&(a%l)%2==1 ? " ":a%l==l-1 ? "|":" "}};print(s)}

```

The reason I include this is because my original thought was to decrease the amount of `for` loops. Whilst this is more verbose it only has the one iteration (also it took me quite a long time so here it is again in a more friendly format):

```
func r(w: Int, h: Int) {
    let l = w * 2 + 3
    var str = ""
    if w + h < 3 {
        str = "o"
    } else {
        for a in 0..<(h + 2) * l {
            if a < l {
                str += "_"
                continue
            }
            if a >= (h + 2) * l - l {
                str += a % l == 0 ? "\n-" : "-"
                continue
            }
            let v = a % l > 0 && a % l < l - 2
            str += a % l == 0 ? "\n|" : v && (a % l) % 2==0 ? "0" : v && (a % l) % 2 == 1 ? " " : a % l == l - 1 ? "|" : " "
        }
    }
    print(str)
}

```

There are a **lot** of ternary conditions here so I'm sure it can be optimised further.
> 0 votes

# Answer
# MAWP, 131 bytes

```
@1A{1M\}>1M!//~[1A~!~]%~!2W3M[1A95W2W5M;]%~
[1A25W;65W1M4W;~[1A84W;77W2W43W1MM;]%~84W;65W1M4W;]~25W;2W3M[1A95W;]

```

The special case was a pain, but I managed to 'golf' a solution under 150 bytes here.

### Output

```
4 3
___________
| o o o o |
| o o o o |
| o o o o |
-----------

```

Try it!
> 0 votes

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


title: Nearest partition numbers

text:
# Question
Title: Nearest partition numbers
The number of partitions of an integer is the number of ways that integer can be represented as a sum of positive integers.

For example:

```
5
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1

```

There are 7 ways to represent the number 5, therefore 7 is the partition number corresponding to the number 5.

Partition numbers: OEIS: #A000041

# Directions

Write a program that takes a positive integer as input, and outputs the two numbers that **generate** the two closest partition numbers to the input number.

* Input must be 1 positive integer.
* If the input **is not** a partition number, the output must be the 2 different positive integers that generate the two closest partition numbers to the input number. (If two partition numbers are equal candidates for one of the output numbers, it doesn't matter which one you choose.)
* If the input **is** a partition number, the output must be 1 positive integer that generates the input number.
* Input and output may be in any reasonable format.
* You may assume that the input will not be larger than 100 million (eg. output will never be larger than 95).
* Built-in functions to calculate partition numbers are **not** allowed, along with other Standard loopholes.
* This is , so least number of bytes wins.

Partition numbers: OEIS: #A000041

# Examples

```
Input: 66
Output: 11, 12

```

(The partition numbers that correspond to the numbers 11 and 12 are 56 and 77, which are the two closest partition numbers to 66.)

```
Input: 42
Output: 10

```

(The number 42 is already a partition number, so just output the number that corresponds to the partition number.)

```
Input: 136
Output: 13, 14

```

(The two closest partition numbers to 136 are actually both LESS than 136 (eg. 101 and 135), therefore the output is 13 and 14 as opposed to 14 and 15.)

```
Input: 1
Output: 0   or   1

```

(Both 0 and 1 are valid outputs in this special case.)

```
Input: 2484
Output: 26, 25   or   26, 27

```

(Both of these outputs are valid, because 2484 is equal dstance from 1958 and 3010.)

```
Input: 4
Output: 3, 4

```

(Yup)

# Answer
# Pyth, 53

```
L?!b<b1sm&d*^_1tdy-b/*dt*3d2r_bhbJo^-QyN2U99<J-2qQyhJ

```

Explanation and more golfing to follow.
> 2 votes

# Answer
# Python 2, 179 bytes

```
Z=range(1,99)
R=Z+[1]
for i in Z:R[i]=sum(-(-1)**k*(3*k*k-k<=i*2and R[i-k*(3*k-1)/2])for k in range(-i,i+1)if k)
f=lambda n:zip(*sorted((abs(n-R[i]),i)for i in Z))[1][:2-(n in R)]

```

Uses the recursive formula from Euler's pentagonal theorem.

Call with `f(2484)`. Output is a tuple with one or two numbers.
> 4 votes

# Answer
# Mathematica, ~~124~~ 123 bytes

```
f@n_:=(p=SeriesCoefficient[1/Product[1-x^k,{k,#}],{x,0,#}]&;s=SortBy[Range@95,Abs[n-p@#]&];If[p@s[[1]]==n,s[[1]],s~Take~2])

```

Formula for partition numbers taken from the OEIS page. (May or may not be cheating... I couldn't decide.)

Usage:

```
In: f[136]

Out: {14, 13}

```

I'm not answering to win. And I'm sure this could be golfed further.
> 2 votes

# Answer
# Jelly, 17 bytes

```
eⱮRŒṗẈrƝƲTµ;‘ṁ3ḊQ

```

Try it online!

Outputs in reverse order.

I think this just about follows the rule "Built-in functions to calculate partition numbers are not allowed", as this uses the Jelly builtin to calculate the *list* of integer partitions, not the *number* of partitions. For example, `4Œṗ => [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]`.

## How it works

```
eⱮRŒṗẈrƝƲTµ;‘ṁ3ḊQ - Main link. Takes an input n on the left
        Ʋ         - Group the previous 4 links together:
  R               -   Take the range 1...n
   Œṗ             -   Calculate the partitions of each k in the range
     Ẉ            -   Take the length of each.
                  -   This gives the kth partition number
      rƝ          -   Insert ranges for each overlapping pair of partition numbers
 Ɱ                - For each of the list of ranges...
e                 -   Yield 1 if n is in the range between the kth and (k+1)th partition number and 0 otherwise
         T        - Remove 0s and replace 1s with their index
                  - For partition numbers, this yields two values. If m is the desired output, this yields [m-1, m]
                  - For non-partition numbers, this returns [m], when the required output is [m, m+1]
          µ       - Set the return value to either U = [m-1, m] or U = [m]
            ‘     - Yield [m, m+1] or [m+1]
           ;      - Concatenate to U, giving either [m-1, m, m, m+1] or [m, m+1]
             ṁ3   - Mold to length 3, giving either [m-1, m, m] or [m, m+1, m]
               Ḋ  - Remove the first value, returns [m, m] or [m+1, m]
                Q - Remove duplicates and output either [m] or [m+1, m]

```
> 1 votes

---
Tags: code-golf, number-theory, integer-partitions
---


title: ASCII art Bresenham line drawing

text:
# Question
Title: ASCII art Bresenham line drawing
Write the shortest possible program that draws a Bresenham line in ASCII art. Your program should take two integers `x` and `y` (command line or stdin, your choice) and draw an ASCII line which starts in the upper left and goes right `x` units and down `y` units. You must use `_` and `\` characters and place them in the correct location according to Bresenham's algorithm.

You may assume `x >= y`, so no vertical segments are required.

Note that because you're using the `_` character, for a line with `y=3` you will likely need to output 4 lines of text (and you may emit a leading blank line when it isn't necessary).

examples:

```
11 3
_
 \___
     \___
         \_
11 1
_____
     \_____

5 4

\
 \_
   \
    \

```

For points which are exactly halfway you may choose either rounding:

```
10 1
____
    \_____
or
_____
     \____

```

# Answer
# Perl, 74

```
/ /;print int(.5+$_*$'/$`)>int(.5+--$_*$'/$`)?$/.$"x$_.'\\':'_'for 1..$`

```

Run with `-n` option (counted in code size).

```
$ perl -n bresenham.pl <<<'11 3'
_
 \___
     \___
         \_
$ perl -n bresenham.pl <<<'11 1'
_____
     \_____
$ perl -n bresenham.pl <<<'5 4'

\
 \_
   \
    \
$ perl -n bresenham.pl <<<'10 1'
____
    \_____

```
> 7 votes

# Answer
# C ~~136~~ 123 Characters

```
z,x,y,i,f;main(){for(scanf("%d%d",&x,&y);i<=x;i++){f=f?printf("_"):1;z+=y;if(2*z>=x&&i<x)f=0,z-=x,printf("\n%*c",i+1,92);}}

```
> 5 votes

# Answer
# Delphi, 109 bytes

Quite small if you ask me :

```
var x,y,i:Word;begin Read(x,y);for i:=1to(x)do if(i*y+x div 2)mod x<y then Write(^J,'\':i)else Write('_')end.

```

The 2 integers are read from the command line.

The newline is written by the seldomly used `^J` syntax (meaning LineFeed), the following '`\`' character is indented using the little-known syntax :`Write(string:width)`.

It's a pitty Delphi `div` for integer-divide (instead of just `\`). Ah well...
> 5 votes

# Answer
# APL (Dyalog Classic), 39 bytes

```
{⍉↑(-1++\a)↑¨'_\'[a←-2-/⌊.5+⍵×⍺÷⍨⍳1+⍺]}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 22 bytes

```
Ｆ…·¹θ⎇‹﹪⁺×ιη⌊∕θ²θη¶\¦_

```

It took a while to figure out the right formula, but it now works! Credit to the Delphi answer.

Link is to verbose version of code.

Try it online!
> 1 votes

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