title: Polyglot the (non constant) OEIS!

text:
# Question
Title: Polyglot the (non constant) OEIS!
*Disclaimer: This is heavily inspired by "Polyglot the OEIS!" but fixes the problem that lead to closure (see the output section) and was re-posted as to not invalidate answers.*

## Introduction

We all know and love the *on-line encyclopedia of integer sequences* (OEIS). So what if we made an *off-line* version of the interesting sequences? Well, that would be kinda too easy, wouldn't it and how would you select a sequence with our standard interface!? No. We need an easier solution to this. A polyglot!

## Input

Your input will be a non-negative integer `n`.

## Output

Your output will either be

* The `n`-th entry of an OEIS sequence OR
* The first `n` entries of an OEIS sequence.

You may take the index to be 1-based or 0-based as you prefer.

To not make this question a duplicate of *The versatile integer printer* **constant sequences are banned.** This should also increase the difficulty level of submissions and avoid "boring" solutions ;)

A sequence is non-constant if there exist two sequence members that are unequal.

## Uhm, so where is the Challenge?

You have to polyglot the above functionality. That is if you support languages A, B and C all must implement different OEIS sequences. The choice of sequence is not limited except that you need different ones for all languages.

That is, if you run the provided program in language A, then sequence X shall be generated, if you run the provided program in language B, then sequence Y shall be generated (with X!=Y) and if you run the provided program in language C, then sequence Z shall be generated (with X!=Z && Y!=Z).

## Who wins?

The answer with the most sequence/language pairs wins. First tie-breaker is code-size (in bytes) with lower being better. Second tie-breaker is submission time with earlier being better.

## Any final Words / Rules?

* You must declare which language will generate which sequence.
* Standard I/O rules apply.
* If different encodings are used between languages, both programs must use the same byte-sequence.
* Language (Python 2/3) revisions *do* count as different languages. Different implementations of a language (such as Browser JS vs Node.js) also count as different languages.
* Standard loopholes apply.

# Answer
# 3 languages (1 byte) - Pyth (A001477), MATL (A000027), Braingolf (A000217)

```
Q

```

---

# How?

`Q` does the following:

* In MATL, it means `+ 1`, so it basically evaluates to `input + 1`.
* In Pyth, it means input, so it just outputs the input.
* In Braingolf, it is the built-in for triangular numbers.

## Mini-polyglot

**Pyth** can be replaced by any of the following languages: **GolfScript**, **Pyke**, **Brachylog** or **Brain-Flak**.
> 17 votes

# Answer
# 10 languages, 122 bytes

```
#|A=1:0;~@}{\,[.,];oi
#coding:utf-8
print (0 and gets.to_i-1 or int(input())**(2+(1/2>0)));quit()#⎚Ｉ±Ｎ»
# x
#x%:+.

```

I definitely can add a bunch more. 1-indexed unless otherwise specified.

Note that I may not be up-to-date on TIO links when I'm sure newer changes didn't affect older programs - you can test them if you want to, but copying 10+ new TIO links every time I make a change gets tiring after a bit. I'll copy new ones every 5 updates or so.

# cQuents v0, A000007

Relevant code: `#|A=1:0;`

`#|A` catches the input and is there for Python comments. `=1` means the first item is `1`, `:0` mean the rest are `0`, outputs the `n`th term given input `n`. cQuents v0 has a weird bug/feature that when an unexpected but valid token, such as `;`, is read, it causes parsing to end.

Try it online!

# PingPong, A001478

Relevant code: `#|A=1:0;~@`

***Outputs via exit code.*** 0-indexed.

`#` skips the next char. `=` does nothing here. `1` pushes `1`, and `:` prints `1` to STDOUT. `0` pushes `0`. `)` does nothing. `;` pushes input, `~` pops and pushes `-n-1`. `@` terminates. The exit code is the top of the stack.

Try it online!

# axo, A001477

Relevant code: `}{\`

0-indexed. `}` reads and pushes an integer from STDIN (requires trailing newline for some reason), `{` prints an the top of stack, and `\` ends the program. I'm not sure what the preceding characters do, but nothing that matters in this case.

Try it online!

# brainfuck, A000027

Relevant code: `,[.,]`

Simple cat program from esolangs.org. Outputs the input.

Try it online!

# \>\<\>, A000030

Relevant code: `#` ... `;oi`

`#` mirrors and wraps to the right, which direct it to read `io;`, which outputs the first character of the input. 0-indexed.

Try it online!

# Ruby, A023443

Relevant code: `print (0 and gets.to_i-1` ... `)`

0-indexed. Prints the input minus 1. `0` is truthy in Ruby, but falsey in Python.

Try it online!

# Python 3, A000578

Relevant code: `print (0 and gets.to_i-1 or int(input())**(2+(1/2>0)));quit()`

Ripped off of HyperNeutrino's original post, but it's a pretty well-known polyglot. `quit()` ends the program.

Try it online!

# Python 2, A000290

Relevant code:

```
#coding:utf-8
print (0 and gets.to_i-1 or int(input())**(2+(1/2>0)));quit()

```

`#coding:utf-8` is required for the Charcoal stuff to work. Also ripped off of HyperNeutrino's original post. `quit()` ends the program.

Try it online!

# Charcoal, A001489

Relevant code: `⎚Ｉ±Ｎ»`

0-indexed.  clears the console (Charcoal prints ASCII as-is) and `Ｉ±Ｎ` prints the negative of the input. `»` is a parse error and terminates the program.

Thanks to ASCII-only for help in chat.

Try it online!

# Cardinal, A020725

Relevant code:

```
 x
x%:+.

```

Adds 1 to the input, and squashes all other pointers.

Try it online!
> 16 votes

# Answer
# 5 languages (05AB1E, Actually, CJam, Jelly, MATL), 7 bytes

```
UD>li)+

```

Try it online!:

* **05AB1E**: sequence A000027 (positive integers: *a*(*n*) = *n*; 1-based)
* **Actually**: sequence A023443 (non-negative integers including 1: *a*(*n*) = *n*−1; 0-based)
* **Cjam**: sequence A020725 (positive integers excluding 1: *a*(*n*) = *n*+1; 1-based)
* **Jelly**: sequence A005843 (non-negative even numbers: *a*(*n*) = 2\**n*; 0-based)
* **MATL**: sequence A000290 (squares: *a*(*n*) = *n*2; 1-based). Exits with an error after producing the output.
> 11 votes

# Answer
# 3 languages: Proton, A000583; Python 3, A000578; Python 2, A000290

## Proton, 49 bytes

```
print(int(input())**(2+(1/2>0)+((''',''')!=',')))

```

Try it online!

## Python 3, 49 bytes

```
print(int(input())**(2+(1/2>0)+((''',''')!=',')))

```

Try it online!

## Python 2, 49 bytes

```
print(int(input())**(2+(1/2>0)+((''',''')!=',')))

```

Try it online!

# Explanation

Proton doesn't have `'''...'''` strings, so `(''',''')` becomes `('' ',' '')`, which somehow doesn't cause issues. It evaluates to `''`, making `(''',''')!=','` evaluate to `True`.

Python does have these strings, so `(''',''')` is just `','` so `(''',''')!=','` evaluates to `False`.

Python 2 uses floor division for integers, so `1/2>0` is false in Python 2 and true in Python 3.
> 8 votes

# Answer
## 5 Languages, 107 bytes

```
s=1/2;1//2;q=int(input())*([2,3][s>0]);"""/.__id__;'
alert(+prompt()+1);`"""#=;#';q=gets
print(q)#)|<>%2)#`

```

### Perl: A000035

Using `=` as a delimiter for `s///` means we can easily exclude code we don't want, and using `)` as the delimiter for `q{}` means after `print`ing `q` in all other languages, we can just work on `<>` directly, without worrying.

```
s/1...q/i...#/;
print(<>%2)

```

Try it online!

### Ruby: A001477

In Ruby, `//` is actually `/` (divide by) `/.../` (regex match), so as long as the regex is terminated, and converted to a number, we can divide by it safely. `__id__` is shorter than `.to_s.ord`, then we just contain the rest of the code we don't want in `'`s, set `q` to `gets` and `print` it with all the others.

```
s=1/2;1//2..."/.__id__;'...';q=gets
print(q)

```

Try it online!

### Python 2: A005843

Using the standard trick to differentiate 2 from 3 and enclosing stuff we don't want in `"""` and comments.

```
s=1/2;1//2;q=int(input())*([2,3][s>0]);"""/...`"""
print(q)

```

Try it online!

### Python 3: A008585

Try it online!

### JavaScript (ES6 browser): A000027

Pretty straightforward for JS, it ended up being easier not to re-use the existing `print` and go for SpiderMonkey, but that might also be possible too.

```
s=1/2;1//2;q=int(input())*([2,3][s>0]);"""/.__id__;'
alert(+prompt()+1);`"""#=;#';q=gets
print(q)#)|<>%2)#`
```
> 6 votes

# Answer
# 6 languages: Cubically 5/6/7/8/9/10, ~~44~~ ~~40~~ 32 bytes

Crossed out 44 is still regular 44 ;(

```
DDR'DDR$:_0?{R'DDRDDB'%0}!{+00%}

```

This prints:

Explanation:

```
DDR'DDR$:_0?{R'DDRDDB'%0}!{+00%}
DDR'DDR                            get top face sum to 2 (all versions)
       $:                          read input and set notepad to it
         _0                        set notepad to input modulo 2
           ?{...........}          if truthy
             R'DDRDD                reset cube
                    B'              set top face to Cubically version number
                      %0            print top face
                         !{....}   if falsy
                           +00      add 2 to notepad twice
                              %     print

```

Try it online! (Cubically 6x6x6)
> 3 votes

---
Tags: code-challenge, sequence, polyglot, rosetta-stone
---


title: Syllables in a Number

text:
# Question
Title: Syllables in a Number
Make a program/function which takes in an integer from 0 to 999999999999 (inclusive) as input and returns how many syllables it has when spoken in English. Make your code short.

**Specification**

* A billion is a thousand million, a trillion is a million million, etc.
* A million has three syllables -- it's mill-ee-on, as opposed to mill-yon. Pronounce all -illions like this.
* Numbers like 1115 are 'one thousand, one hundred *and* fifteen'. The 'and' counts as a syllable.
* 0 is zero. That's two syllables.

I know the specification seems mishmash in terms of which standards are used (British or American, mainly) -- it's what I and everyone I know use. I would change it so it's consistent, but someone's already answered...

**Test Cases**

```
> 0
2
(zero)

> 100
3
(one hundred)

> 1000001
6
(one million and one)

> 1001000001
10
(one billon, one million and one)

> 7
2
(seven)

> 28
3
(twenty-eight)

> 78
4
(seventy-eight)

> 11
3
(eleven)

> 1111
10
(one thousand, one hundred and eleven)

> 999999999999
36
(nine hundred and ninety-nine billion, nine hundred and ninety-nine million, nine hundred and ninety-nine thousand, nine hundred and ninety-nine)

```

# Answer
> 1 votes
# Python 2, 232 bytes

```
def f(a):o=map(int,format(a,",").split(","));print(a%100>0)*(a>1000)+sum((k%100>0)*(k/100>0)for k in o[:-1])+sum((k>99)*2+`k`.count('7')+(k/10%10>0)+3-`k+1000`.count('0')for k in o)+sum((0<o[~k])*(5-k)*k/2for k in range(len(o)))or 2

```

Try it online!

This still has some potential for golfing, maybe in a lambda. The function splits the input into groups of three digits, each of which have a certain number of syllables. Luckily, every digit is 1 syllable except for 7. Every tens-place adds an extra 1 syllable to the number of syllables of the digit except for 1, which adds 0 (`-teen` or `ten`).

Ungolfed:

```
def f(k):
    a=k
    if a==0:return 2
    o=[]
    while a>0:
        o.append(a%1000)
        a/=1000
    o=o[::-1]
    return \
int(o[-1]%100>0 and len(o)>1)        +len('+1 if first group of three have "and"'[0:0])+\
sum(\
  [int(k%100>0 and k/100>0)        +len('+1 if rest have "and"'[0:0])\
for k in o[:-1]])+
sum(\
  [int(k>99)*2                      +len('have "hundred"'[0:0])\
  +str(k).count('7')               +len('+1 for "se-ven"'[0:0])\
  +(k/10%10>0)                    +len('+1 for "-ty" e.g. nine-ty'[0:0])\
  +3-str(k+1000).count('0')        +len('+1 for each number'[0:0])\
for k in o])+\
sum(\
  [int(o[-(k+1)]>0)*([0,2,3,3][k])  +len('add 2 if "thousand", add 3 if "million", add 3 if "billion"'[0:0])\
for k in range(len(o))])

```

*-12 bytes thanks to @Mr.Xcoder*

---
Tags: code-golf, integer, natural-language
---


title: Is this a losing square?

text:
# Question
Title: Is this a losing square?
There is a game called *Get Home* that is played on the a chess board. In this game there is a single piece that is moved by both players in turns. There are some rules to how the piece can be moved. On a turn a player must make one of the following moves for positive **n**.

* **n** spaces up
* **n** spaces to the left
* **n** spaces up and to the left (a diagonal)

The player who moves the piece into the top left corner of the board wins the game.

Now we will define the concept of a losing square. In this video (from where I got the idea) a losing square is defined as a square on which, any player starting their turn will be forced to make a move allowing their opponent to force a win. The simplest example of a losing square would be the square at (1,2). A piece at (1,2) can move to any of the following places.

All of which have a direct path to victory for the next player.

It also follows that any square that has a one move path to a losing square allows the player starting on that square to force a win. This means that any square that is not one move away from a losing square is also a losing square.

This brings us to this rather neat definition of a losing square:

A losing square is a square from which no move can arrive on another losing square and (0,0) is a losing square.

# Task

Given the coordinates of a square on an arbitrarily sized chess board determine if it is a losing square. Output two values one for losing squares and one for others.

This is so answers will be scored in bytes with less bytes being better.

# Test Cases

Here are all the losing squares on a regular 8 by 8 chess board (marked with 0).

```
0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1
1 0 1 1 1 1 1 1
1 1 1 1 1 0 1 1
1 1 1 1 1 1 1 0
1 1 1 0 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 0 1 1 1

```

Here is an image of a 100 by 100 board with losing squares marked in black (each square is 2 pixels by 2 pixels).

# Answer
# Python 3, 112 50 46 42 bytes

-4 bytes thanks to Jonathan Allan!

-2 bytes thanks to xnor!

```
lambda r,c:abs(r-c)*(3+5**.5)//2==max(r,c)

```

Try it online!

Based on the formula for cold positions in Wythoff's game and making some modifications in order to produce an explicit formula. Explanation inbound once I actually finish a proper methodology for the derivation of the formula.
> 8 votes

# Answer
# Jelly, 8 bytes

```
ạ/×ØpḞ⁼Ṃ

```

**Try it online!**, or see the top-left 60 by 60 as a grid.

### How?

A cold position in Wythoff's game is a losing position. The coordinates `[n,m]` give a cold position when `n = floor(kφ) = floor(mφ) - m` or `m = floor(kφφ) = ceil(nφ) = n + k` for some natural number, `k`, and the golden ratio, `φ`. The former holds when `n` is less than `m`; the latter when `m` is less than `n` (both holding at `0,0`).

`k` is thus the absolute difference between `n` and `m` and if `floor(abs(n-m)φ)=min(n,m)` the condition is met.

```
ạ/×ØpḞ⁼Ṃ - Link: list, c ([n,m])
 /       - reduce c by:
ạ        -   absolute difference = abs(n-m)
   Øp    - golden ratio yield
  ×      - multiply
     Ḟ   - floor
       Ṃ - minimum of c = min(n,m)
      ⁼  - equal?

```
> 5 votes

# Answer
## JavaScript (ES6), 64 bytes

```
f=(x,y,p=5**.5/2+.5)=>x<y?f(y,x):y/p%p<1&(y/p%p-x*p%++p)**2<1e-9

```

I see now that this is not the best technique, but I had to come up with it myself because I lost internet shortly after loading this page. (Would've posted a while ago if not for these internet issues...)

In a perfect world, float precision wouldn't be an issue and I could save 9 bytes:

```
f=(x,y,p=5**.5/2+.5)=>x<y?f(y,x):y/p%p<1&y/p%p==x*p%++p

```

6 more bytes could be saved if JS supported Python's comparison chaining:

```
f=(x,y,p=5**.5/2+.5)=>x<y?f(y,x):y/p%p==x*p%++p<1

```
> 2 votes

# Answer
# Pyth, 39 Bytes

```
=SQL?!b0-byytb;q@myd+0.fqyZytZ@Q1)-F_Qh

```

I wrote this with a named function (ew), and was extremely lazy with golfing. Planning to golf off quite a number of bytes later tonight

Try it online, with my own generated tests, meant to alternate True / False

Explanation:

Diagonals of the solution matrix have a losing square according to the sequence of repeated numbers in OEIS A005206. From `L` through `;` is pretty straightforward polish notation to define `y(b)=b-y(y(b-1))`.

The rest of the explanation follows

```
=SQL?!b0-byytb;q@myd+0.fqyZytZ@Q1)-F_Qh    Full program, take stdin as [x, y], output True or False to stdout
=SQ                                        Sort input
   L?!b0-byytb;                            Named lambda as explained above
                    +0.f                   Make sequence of first max(x, y) numbers, starting with 0,
                        qy y               For which are equal
                          Z tZ             each element and the previous are equal
                myd                        Map this sequence to the y(index), not just index numbers
             q                             Check if are equal
              @                  )-F_Q     the x-yth element of sequence (x-y represents which diagonal)
                                     h(Q)  and the lower of [x,y] (Q is added by the interpreter to fix arity issues

```
> 0 votes

# Answer
## Batch, 204 bytes

```
@if %1 lss %2 %0 %2 %1
@if %1==0 exit/b0
@set/au=l=i=0
:g
@set/au+=2+i%%2,l+=1+i%%2
@if %1==%n% if %2==%m% exit/b0
@if %1 leq %n% exit/b1
:l
@set/a"k=3*i^2*i^i,i+=1
@if %k%==0 goto g
@goto l

```

Returns via exit code. Explanation: Since Batch only has integer arithmetic I had to devise a purely arithmetical solution. Excluding the `0,0` entry, the pairs of losing square coordinates follow the following rule: if the next `11`-free binary number is even then add `3,2` otherwise add `2,1`. A test for a `11`-free binary number is if there are no carries when it is multiplied by three, in other words that `(i*2)+i==(i*2)^i`. Here are the first few `11`-free binary numbers and their coordinates:

```
   0     2,1  + 3,2 =  5,3
   1     5,3  + 2,1 =  7,4
  10     7,4  + 3,2 = 10,6
 100    10,6  + 3,2 = 13,8
 101    13,8  + 2,1 = 15,9
1000    15,9  + 3,2 = 18,11
1001    18,11 + 2,1 = 20,12
1010    20,12 + 3,2 = 23,14

```

etc. Mysteriously this rule suffices to make the sequences complementary. It then remains to compute the sequence until it reaches the larger coordinate, at which point we can determine whether the square is losing.
> 0 votes

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


title: Fix my Fat Fingers

text:
# Question
Title: Fix my Fat Fingers
# Code Golf Challenge

I have an isdue, my fingrrs are fat and I freqintly jave an isdue of ty\[ing one keystrpke to the right on my kryboard.

I'm afraid the isdue is getyng worse anf worsr as time goes on.

Sopn every keystrpke I make wil; be shiftrd pne to the right!

Befpre then I'd like a program (or functipn) to autp shift every keystrpke back to the left one.

I'll make sure to take my tome typong the rest of tjis chal;enge so as not to cause anu confudion!

---

# Objective:

Write a program or function that takes an input of one of the following green keys on a standard QWERTY keyboard and returns the character of the key one to the left of it.

---

# Conditions:

•You may assume that the person running this program is using a QWERTY keyboard like the one pictured above.

•Input and Output are both case-insensitive, you may use any case (or a mixture of case combinations) for this challenge and you can also assume all input will be in one case if desired.

•If your language has no way of allowing a user to input the return key for some reason you may ignore that one keystroke for this

•This challenge is just for the default values of the keys, for example if the `4` key is pressed you can assume it will always be `4` and never `$`

•You can assume only the green keys will ever be pressed.

---

# Example `Input` -\> `Output`:

`S` -\> `a`
`4` -\> `3`
`=` -\> `-`
`[` -\> `p`

---

This is , so the program with the shortest bytecount wins!

# Answer
## Ruby, ~~76 71~~ 69 bytes

```
->a{"`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./"[/.#{a}/][0]}

```
> 7 votes

# Answer
# Perl 6, ~~87~~ ~~83~~ 69 bytes

~~```
{[Q"`1234567890-=qwertyuiop[]\asdfghjkl;'
zxcvbnm,./".comb].&{%(.[1..*]Z=>$_)}{$_}}

```~~
```
{~Q"`1234567890-=qwertyuiop[]\asdfghjkl;'
zxcvbnm,./".match(/.)>$_/)}

```

Try it online!

Wondering if there's a way to encode that hard-coded string to something shorter...

*(Stole G B's regex idea for -14 bytes.)*
> 5 votes

# Answer
# Jelly, ~~34~~ 33 bytes

```
ØD”`1¦ṭØqż“[]\“;'¶“,./“0-=”Fṡ2UZy

```

Try it online!

### How it works

```
ØD”`1¦ṭØqż“[]\“;'¶“,./“0-=”Fṡ2UZy  Main link. Argument: s (string)

ØD                                 Digits; yield "0123456789".
  ”`1|                             Replace '0' with a backtick.
       Øq                          Qwerty; yield
                                   ["qwertyuiop", "asdfghjkl", "zxcvbnm"].
      ṭ                            Tack; add "`123456789" as the last element of
                                   the qwerty array.
          “[]\“;'¶“,./“0-=”        Yield ["[]\\", ";'\n", "0-="].
         ż                         Zip; combine the strings of the array to the
                                   left with the corresponding strings of the array
                                   to the right, yielding an array of string pairs.
                           F       Flatten, yielding a string.
                            ṡ2     Obtain all overlapping pairs of characters.
                              U    Upend; reverse each pair.
                               Z   Zip, yielding a pair of strings.
                                y  Translate the input s according to the generated
                                   replacement table.

```
> 5 votes

# Answer
# Python 3, ~~85~~ 78 bytes:

```
lambda x,k="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm<>?":k[k.find(x)-1]

```
> 4 votes

# Answer
# Retina, 53 51 bytes

```
T`1-90\-=QW\ERTYUI\OP[]\\ASDF-HJ-L;'¶ZXCVBNM,./`\`o

```

Try it online!

A simple transliteration shifting every character 1 position backwards. Everything from `1` to `/` is the original character set, while the following part is the new set, using `o` to indicate the Other set.

`H` and `L` are special character classes for transliteration in retina (respectively mapping to Hex digits and uppercase Letters), but fortunately they occur on the keyboard inside alfabetically ordered sequences (`FGH` and `JKL`), so we can avoid escaping them by putting them in ranges and gain like that 2 bytes.
> 4 votes

# Answer
# Python, 76 bytes

```
s="1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm<>?"
dict(zip(s,'`'+s)).get

```

Try it online!

Makes a dictionary that takes each key to the one to its left by zipping the character string with its shifted version. The bottom line is the function, the top one is a definition.

Using `translate` to create a mapping gave a longer solution. Try it online!

```
lambda s:s.translate("';"*22+"_0__9`12345678_LM-<>_\\VXSWDFGUHJKNBIO=EARYCQZT\nP][___"*4)

```
> 4 votes

# Answer
# , ~~57~~ ~~54~~ 51 bytes

*3 bytes saved thanks to @nmjcman101 for using `hxVp` instead of what I had for the multiline keyboard*

```
i`¬190-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./<esc>/<C-r>a
hxVp

```

Try it online!

`<esc>` is `0x1b` and `<c-r>` is `0x12`

Note: this doesn't not support the enter key

Contains unprintables, so here's the hexdump

```
00000000: 6960 ac31 3930 2d3d 7177 6572 7479 7569  i`.190-=qwertyui
00000010: 6f70 5b5d 5c61 7364 6667 686a 6b6c 3b27  op[]\asdfghjkl;'
00000020: 7a78 6376 626e 6d2c 2e2f 1b2f 1261 0a68  zxcvbnm,././.a.h
00000030: 7856 70                                  xVp

```

### Explanation

Most of the program generates the keyboard. `i` enters insert mode and every character following it is printed to the buffer. But there is a small quirk here, `¬19` inserts characters between 1 and 9.

The program exits insert mode at the `<esc>`. And then here `/<c-r>a` it searches for the argument in the buffer. This brings the cursor on top of the character it found.

```
h                  " move the cursor to the left
 x                 " delete this character
  Vp               " select this line and replace it with the deleted character

```
> 3 votes

# Answer
# C++, 109 bytes

```
void f(char i){std::string k="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./";std::cout<<k[k.find(i)-1];}

```

Try it online!
> 3 votes

# Answer
# TI-Basic, 70 bytes

I doubt that it could get any shorter than this...

```
Input Str1
"`1234567890-=QWERTYUIOP[]\ASDFGHJKL;'ZXCVBNM,./
sub(Ans,inString(Ans,Str1)-1,1

```

P.S. The two-byte tokens are `Str1`, ```, `\`, `sub(`, and `inString(`.
> 3 votes

# Answer
# Japt, 56 42 bytes

```
;D=Dv ·q i"[]\\",A i";'",22 +",./")Dg1nDbU

```

### Explanation

```
;D=Dv ·q i"[]\\",A i";'",22 +",./")Dg1nDbU

;D=D                                        // Shortcut for QWERTY (with newlines and spaces), assigning to variable D
    v                                       // Setting D to lowercase
      ·q                                    // Joining D into an array with no spaces or newlines
        i"[]\\",A                          // Inserting "[]\" into index 10 (A)
                   i";'",22                 // Inserting ";'" into index 22
                           +",./"           // Appending ",./"
                                  Dg        // Returns the character at index:
                                    1n      //    -1+
                                       DbU  //     Index of U (the input)

```

Try it online!
> 2 votes

# Answer
# PowerShell, 82 bytes

```
$k="1234567890-=qwertyuiop[]\asdfghjkl;'
zxcvbnm,./";$k[$k.IndexOf((read-host))-1]

```

The Enter key is supported, but cannot be tested with `Read-Host` because the act of hitting enter with no value returns nothing in PowerShell.
> 2 votes

# Answer
## JavaScript (ES6), 74 bytes

```
c=>(s=".,mnbvcxz\n';lkjhgfdsa\\][poiuytrewq=-0987654321`")[s.indexOf(c)+1]

```

Since `/` isn't in my string, `indexOf` returns `-1`, which when incremented causes `.` to be output. 93 bytes to process a string:

```
s=>s.replace(/./g,c=>s[s.indexOf(c)+1],s="><mnbvcxz\n';lkjhgfdsa\\][poiuytrewq=-0987654321`")

```
> 2 votes

# Answer
# Java 8, 99 bytes

```
c->{String r="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./";return r.charAt(r.indexOf(c)-1);}

```

**Explanation:**

Try it here.

```
c->{                // Method with character as both parameter and return-type
  String r="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./";
                    //  Literal String of the qwerty keyboard layout of the challenge
  return r.charAt(  //  Return the character at the following index:
    r.indexOf(c)    //   The index of the input character
    -1);            //   -1 to shift it to the left
}                   // End of method

```
> 2 votes

# Answer
## GNU sed, 72 + 1(r flag) = 73 bytes

```
s:$:`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./:
s:(.).*(.)\1.*:\2:

```

The return key can't be tested, because sed by design splits the input using `\n` as the delimiter and then runs the script as many times as there are lines.

**Test run:** continuous input-output pair (when done press Ctrl + D or Ctrl + C)

```
me@LCARS:/PPCG$ sed -rf shift_key.sed
s
a
4
3
=
-
a
\
1
`
\
]

```
> 1 votes

# Answer
# 05AB1E, 50 bytes

```
'`žhÀ"-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./"JDÀ‡

```

Try it online!

Explanation:

```
'`                                                  # 1 char string: `
  žh                                                # Push numbers 0123456789
    À                                               # Rotated 1 left (123456890)
     "-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./"      # Push string literal
                                              J     # Join all elements pushed to the stack to one string
                                               D    # Duplicate
                                                À   # Rotate 1 left
                                                 ‡  # Transliterate: a.get(b.indexOf(input))

```
> 1 votes

# Answer
# Pyth - 56 bytes

```
@K"`1234567890-=qwertyuiop[]\\asdfghjkl;'
zxcvbnm,./"txK

```

Test Suite.
> 1 votes

---
Tags: code-golf, keyboard, hardware
---


title: Detonate a string

text:
# Question
Title: Detonate a string
Given any string, print it in the form of a triangle where the text runs up and down along each diagonal. For example, an input of `"Hello World"` should output:

```
                    d
                  l
                r   d
              o   l
            W   r   d
              o   l
        o   W   r   d
      l       o   l
    l   o   W   r   d
  e   l       o   l
H   l   o   W   r   d
  e   l       o   l
    l   o   W   r   d
      l       o   l
        o   W   r   d
              o   l
            W   r   d
              o   l
                r   d
                  l
                    d

```

The space between each character in a row must be at least 1, in order to maintain the proper format.

# Answer
> 19 votes
# Charcoal, ~~10~~ 7 bytes

```
↗ＥＬθ✂θι~~ＵＥ¹~~
```

~~Try it online!~~ Try it online! Links are to verbose version of code. Explanation:

```
    ↗       Print up and to the right
     ＥＬθ✂θι All suffixes of the input, as a list down and to the right
    ~~ＵＥ¹~~     ~~Insert blank columns~~
```

~~First time I got to use the `ＵＥ` command.~~

# Answer
> 12 votes
# 05AB1E, ~~10~~ ~~8~~ 7 bytes

Thanks to *Emigna* for saving 2 bytes!

```
ðâƶ.cðζ

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 9 votes
# Python 2, 75 bytes

```
s=input()
k=l=len(s)
while k>1-l:k-=1;m=abs(k);print' '*m+' '.join(s[m::2])

```

Try it online!

Ruud saved 3 bytes.

# Answer
> 8 votes
# C, ~~86~~ ~~78~~ ~~73~~ 70 chars

```
for(int i=1,j=1-n;i=putchar(j*j<i*i&i-j?s[i-1]?:13:32)^13?i+1:++j<n;);

```

Try it online!

### Explanation

Naive implementation: two cycles, fill from top to bottom, left to right (99 bytes):

```
for(int j=1;j<n*2;j++){for(int i=0;i<n;i++)printf("%c ",(i+j)%2&&i+1>=abs(j-n)?s[i]:' ');puts("");}

```

Here, puts() just prints \n to the output. Let’s combine variable declarations and combine j++ with something (94 bytes):

```
for(int i,j=0;++j<n*2;){for(i=0;i<n;i++)printf("%c ",(i+j)%2&&i>=abs(j-n)?s[i]:' ');puts("");}

```

Good. Variable j has a range 0...2n; let it be within -n...n, this makes the math simpler. Notice that boolean expression at the right of && always has the value 0 or 1. This means we can replace && with &. 91 byte:

```
for(int i,j=-n;++j<n;){for(i=0;i<n;i++)printf("%c ",~(i+j)%2&i>=abs(j)?s[i]:' ');puts("");}

```

And now we realized we printing an extra space. And yeah, we don’t need printf() to print just a single symbol. 86 bytes:

```
for(int i,j=-n;++j<n;){for(i=0;i<n;i++)putchar(~(i+j)%2&i>=abs(j)?s[i]:' ');puts("");}

```

Even better. Notice that condition i * i\>=j * j is same as i\>=abs(j), but shorter. Let’s move puts() into for loop increment expression. And guess what? Actually, we don’t need the braces around i+j. 78 bytes:

```
for(int i,j=-n;++j<n;puts(""))for(i=0;i<n;i++)putchar(i*i>=j*j&~i+j?s[i]:' ');

```

Did you know that putchar() returns the character it has printed? Let’s use XOR to test numbers for equivalence. Let’s replace space with its ASCII code, 32. Remember that end-of-line character code is 13. And finally: did you know that GCC/Clang do support https://en.wikipedia.org/wiki/Elvis\_operator ? 73 bytes:

```
for(int i,j=-n;++j<n;)for(i=0;putchar(i*i>=j*j&~i+j?s[i]?:13:32)^13;i++);

```

Finally, guess what? We don’t need two for loops. We can replace ugly ~i+j with just i-j. 70 bytes:

```
for(int i=1,j=1-n;i=putchar(j*j<i*i&i-j?s[i-1]?:13:32)^13?i+1:++j<n;);

```

Future work: change loop direction? This might save some bytes, if done properly.

# Answer
> 5 votes
# SOGL V0.12, ~~13~~ ~~10~~ 9 bytes

```
ēI*@∑}¹╚H

```

This uses a feature that I just added, but was documented a while ago.

Try it here!
In that link `,` is added because this expects the input on the stack and `{` added because otherwise `,` would get executed every time in the loop

```
implicitly start loop over POP
ē            increase the variable E, on first push which will be 0
 I           increase by 1
  *          multiply the current character that many times
   @∑        join with spaces
     }     end loop
      ¹    wrap everything on stack in an array
       ╚   center vertically
        H  rotate counter-clockwise

```

# Answer
> 4 votes
# Haskell, 73 bytes

```
f s|l<-length s-1=[zipWith min s$(' '<$[1..abs x])++cycle"~ "|x<-[-l..l]]

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~86~~ 83 bytes

-3 thanks to officialaimm

```
lambda s,j=' '.join:map(j,zip(*(j(c*-~i).center(len(s)*2)for i,c in enumerate(s))))

```

Try it online!

# Answer
> 3 votes
# Gaia, 16 bytes

```
$:ċ⟪×$§×⟫†€|$¦tụ

```

Try it online!

### Explanation

```
$                 Split into list of chars
 :ċ               Push [1 .. len(input)]
   ⟪×$§×⟫†        Apply this block to corresponding elements of the two lists:
    ×              Repetition
     $             Split into chars
      §×           Join with spaces
          €|      Centre align the rows
            $¦    Split each line into chars
              t   Transpose
               ụ  Join each row with spaces, then join the rows together with newlines

```

# Answer
> 3 votes
# Jelly, 15 bytes

```
;€⁶ṁ"JUz⁶ZUŒBZG

```

Try it online!

# Answer
> 3 votes
# Octave, ~~59~~ ~~63~~ ~~58~~ 57 bytes

```
@(s,a=@strjust)a([kron(+a(hankel(s)),[1 0;0 0]) '']',99)'

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~140~~ 137 bytes

```
(m#n)s=(\(i,x)->' ':(last$"  ":[x:" "|rem i 2==m&&i>n]))=<<zip[0..]s
g s=((++)=<<reverse.tail)$id=<<[[(0#n)s,(1#n)s]|n<-[-1,1..length s]]

```

Try it online!

*Saved 3 bytes thanls to Challenger5*

I don't think that's optimal...

`f` produces one of the lines (`m` = 0 or 1 is the modulo of the line number, `n` is the number of the line)

`g` intercalates "odd" and "even" lines, and add to the result a mirror of itself.

# Answer
> 3 votes
## Java, 292 bytes (sorry)

```
public class D{
public static void main(String[]r){
String s=r[0];int L=s.length(),n=L*2-1,x=L-1,d=-1,i,j;boolean a=false,o=L%2==1;
for(i=0;i<n;i++){
for(j=0;j<L;j++)System.out.print(j<x||a&&j%2==(o?0:1)||!a&&j%2==(o?1:0)?' ':s.charAt(j));
System.out.println();
x+=d;if(x<0){x=0;d=1;}a=!a;}}}

```

# Answer
> 3 votes
# Haskell, 81 bytes

```
f s|l<-length s=[[last$' ':[s!!i|i>=n,mod(n+i)2<1]|i<-[0..l-1]]|n<-abs<$>[-l..l]]

```

Try it online!

# Answer
> 3 votes
# Java (OpenJDK 8), 116 bytes

```
s->{for(int l=s.length(),i=-l;++i<l;)System.out.printf("%"+l+"s%n",s.substring(i<0?-i:i).replaceAll("(.).","$1 "));}

```

Try it online!

## Explanation

```
s->{                                // Consumer<String> lambda
 for(int l=s.length(),i=-l;++i<l;)  // For each length between l and 1 and back to l,
  System.out.printf("%"+l+"s%n",    // Print with align to right
    s.substring(i<0?-i:i)           // skip the first |i| characters
     .replaceAll("(.).","$1 ")      // replace every even-positioned character with a space.
   );
}

```

# Answer
> 3 votes
# C++, 135 bytes

Okay, here's my shot with C++:

```
auto f=[&](auto f,int y)->void{
  for(int i{};i<n;i++) putchar(y<0?f(f,y+1?i+1:n-1-i),'\n':i<y||i+y&1?' ':s[i]);
}; f(f,-1); f(f,-2);

```

Try It Online (ideone)!

# Answer
> 2 votes
# Pyth, 25 bytes

```
j+_Km++*d;@Qdtj;%2>QdUQtK

```

Try it here.

# Answer
> 2 votes
# Jelly, 18 bytes

```
JrLm€2Ṭ;€0a⁸o⁶ṚŒḄG

```

Try it online!

# Answer
> 2 votes
## Mathematica 105 Bytes

```
(c=Characters@#;l=Length@c;StringRiffle@Table[If[Abs[j-l]<i&&EvenQ[j+i],c[[i]]," "],{j,1,2l+1},{i,1,l}])&

```

Maybe I could shave off another byte or two, but the character count overhead of dealing with strings in Mathematica makes simple challenges like this uncompetitive.

# Answer
> 2 votes
# J, 54 bytes

```
[:|:|.@i.@#(>@],~' '#~[)"_1[:(,' '&,)/&.>>:@i.@#<@#"0]

```

Try it online! (note that the output on TIO has a newline and three spaces, but that isn't from the function call -- it's probably just what the J interpreter does automatically).

I think the general idea for solving this is right, but there are small things that I'm probably doing sub-optimally that are adding to the bytecount.

### Previous variants

55 bytes

```
<:@+:@#{.[:|:|.@i.@#(],~' '#~[)"_1>:@i.@#(,' '&,)/@#"0]

```

56 bytes

```
<:@+:@#{.[:|:|.@i.@#(],~' '#~[)"_1#{.[:(,' '&,)//.[:]\.]

```

# Explanation

This will be split into a few functions. Also, I wasn't as thorough with latter parts of the explanation, so let me know if you want a better explanation for a certain part and I can edit that in.

```
dup   =. >:@i.@# <@#"0 ]
space =. (,' '&,)/&.>
pad   =. |.@i.@# (>@],~' '#~[)"_1 ]
trans =. |:

```
* `dup` duplicates each character as many times as its index (plus one) in the string
* `space` inserts spaces between each character
* `pad` pads the characters with the right amount of spaces
* `trans` transposes the resulting matrix

Sample call:

```
   trans pad space dup 'abc'
  c
 b
a c
 b
  c

```

### Dup

```
>:@i.@# <@#"0 ]
>:@i.@#         Indices of each character plus one
      #          Length of the string
   i.            Range [0,length)
>:               Add one
        <@#"0 ] Duplicate each character as many times as it index (plus one)
           "0   For each
          #   ]  Copy the character
>:@i.@#           as many times as it index
        <        Box the result

```

The results are boxed to prevent J from padding the ends with spaces (since they're of uneven length).

Sample call:

```
   dup 'abc'
┌─┬──┬───┐
│a│bb│ccc│
└─┴──┴───┘

```

### Space

```
(,' '&,)/&.>
         &.>  For each boxed element
(,' '&,)/      Insert spaces between each

```

Sample call:

```
   space dup 'abc'
┌─┬───┬─────┐
│a│b b│c c c│
└─┴───┴─────┘

```

### Pad

```
|.@i.@# (>@],~' '#~[)"_1 ]
        (>@],~' '#~[)      Pad the right arg with spaces given by the left arg
|.@i.@#                    Indices in reverse order
   i. #                     Range [0,length)
|.                          Reverse

```

Basically, pad the first element with length - 1 spaces, the second with length - 2, etc. It also removes the boxing.

Sample call:

```
   pad space dup 'abc'
  a
 b b
c c c

```

### Transpose

This is just the built-in function `|:` which takes the transpose of a matrix.

# Answer
> 1 votes
# Perl 5, 86 + 2 (-F) = 88 bytes

Used @Dom's suggestions and a few of my own tweaks to lower the byte count.

```
for$k(0..$#F){$i=1;$a[$#F+$k]=$a[$#F-$k]=[map$i++<$k|($i+$k)%2?$":$_,@F]}say"@$_"for@a

```

Try it online!

# Answer
> 1 votes
# JavaScript (ECMAScript 6), 161 bytes

```
(s,n=console.log)=>s.split("").map((q,i,a,p)=>n(p=" ".repeat(q=a.length-++i)+a.map((v,j)=>j>=q&&j%2==q%2?a[j]+' ':'').join(''))||p).reverse().map((v,i)=>i&&n(v))

```

Try it online!

# Answer
> 0 votes
# q/kdb+, 55 bytes

**Solution:**

```
-1(+){{1_a,((2*y)#" ",z),a:x#" "}'[(|)c;1+c:(!)(#)x]x};

```

**Example:**

```
q)-1(+){{1_a,((2*y)#" ",z),a:x#" "}'[(|)c;1+c:(!)(#)x]x}"Hello World";
          d
         l
        r d
       o l
      W r d
       o l
    o W r d
   l   o l
  l o W r d
 e l   o l
H l o W r d
 e l   o l
  l o W r d
   l   o l
    o W r d
       o l
      W r d
       o l
        r d
         l
          d

```

**Explanation:**

TODO. ungolfed version is 66 bytes:

```
-1 flip{{1_a,((2*y)#" ",z),a:x#" "}'[reverse c;1+c:til count x]x};

```

**Bonus:**

To get the same output as the example (74 bytes):

```
q)-1(+){1_'raze{(a,((2*y)#" ",z),a:x#" ";(2*y+x)#" ")}'[(|)c;1+c:(!)(#)x]x}"Hello World";
                    d
                  l
                r   d
              o   l
            W   r   d
              o   l
        o   W   r   d
      l       o   l
    l   o   W   r   d
  e   l       o   l
H   l   o   W   r   d
  e   l       o   l
    l   o   W   r   d
      l       o   l
        o   W   r   d
              o   l
            W   r   d
              o   l
                r   d
                  l
                    d

```

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


title: Is it a noun or not?

text:
# Question
Title: Is it a noun or not?
Given a string as input, determine whether it is a noun or not.

You will be scored on the 1000 most common English words, by how many you correctly label as a noun or not.

The program or function which correctly classifies the most of those words in 50 bytes or less will win.

# Nouns

A noun is a word that represents a thing, typically. It gets more complex, but that's the basic idea.

In cases where a word could either be a noun or some other part of speech, I classified it as a noun, even if that's a rare usage. Or actually, I let this site do it for me.

The words you'll be scored on are these 1000 common words, which are from simple Wikipedia, with "two" and "once" added. Of those, these are the 586 nouns, and these are the 414 non-nouns. You can find all three lists here. Note that all of these inputs are in lower case. These lists are final - don't try to argue grammar.

Your program will be considered correct if it outputs a truthy result on an input which is a noun, and a falsy result on an input which is not a noun.

**Subtleties:**

Programs must have a deterministic output. If you want to use randomness, seed it. Programs are not allowed to use built-in noun lists or other built-in part-of-speech functionality.

**Examples:**

```
a: noun
act: noun
active: noun
about: non-noun
above: non-noun
across: non-noun

```

Please indicate what your program's success rate is in your answer. The program or function of at most 50 bytes with the highest success rate wins. In case of a tie, lowest byte count will determine a winner. Good luck!

# Answer
> 13 votes
## JavaScript (ES6), 43 bytes, ~~622~~ ~~630~~ 633

Just to get the ball rolling. Returns `1` for nouns, `0` for non-nouns.

```
s=>2552>>s.length&/^[bcdf-mp-tvwy]/.test(s)

```

### How?

We bet on *noun* if both following conditions are met:

1. The word length is 3, 4, 5, 6, 7, 8 or 11. This is done by right-shifting the binary number 100111111000 (2552 as decimal).
2. The word starts with one of these letters: `bcdfghijklmpqrstvwy`

# Answer
> 11 votes
# JavaScript (ES6), 50 bytes, score 693

```
s=>!/^([aouz]|th|..$)|e.+[ey]|[flo].r|a.p/.test(s)

```

Just looking for any possible patterns that non-nouns have that nouns don't.

Non-nouns more often contain:

1. **a, o, u,** or **z** as the first letter.
2. **th** as the first two letters.
3. Two letters only. \[Think pronouns (me, we, us, he, it) and prepositions (of, to, in, on, by, at, up, ...).\]
4. **e**, followed by one or more letters, followed by **e** or **y**.
5. **f, l,** or **o**, followed by any letter, followed by **r**.
6. **a**, followed by any letter, followed by **p**.

**Snippet:**

```
var nouns = ['a','act','active','activity','age','air','amount','answer','anything','apple','area','arm','army','art','ask','attack',
             'baby','back','bad','bag','ball','bank','base','basket','bath','bear','beautiful','bed','bedroom','beer','bell','big','bird','birth','birthday','bit','bite','black','block','blood','blow','blue','board','boat','body','bone','book','border','bottle','bottom','bowl','box','boy','branch','brave','bread','break','breakfast','bridge','brother','brown','brush','burn','business','bus','buy',
             'cake','call','can','candle','cap','car','card','care','carry','case','cat','catch','chair','chance','change','chicken','child','chocolate','choice','city','class','clock','clothes','cloud','coffee','coat','cold','comfortable','common','computer','condition','control','cook','corner','cost','count','country','course','cover','crash','cross','cry','cup','cut',
             'dance','dark','daughter','day','dead','deep','desk','dinner','direction','dish','dog','door','double','draw','dream','dress','drink','drive','drop','dust','duty',
             'ear','earth','east','eat','education','effect','egg','end','equal','entrance','escape','evening','event','examination','example','exercise','eye',
             'face','fact','fail','fall','family','farm','father','fat','fault','fear','feed','feel','female','few','fight','fill','film','finger','finish','fire','fish','fix','floor','flower','fly','fold','food','foot','football','force','form','freedom','friend','front','fruit','fun','funny','future',
             'game','garden','gate','general','gift','give','glad','glass','go','god','gold','good','grandfather','grandmother','grass','great','green','ground','group',
             'hair','half','hall','hand','hat','hate','head','heavy','heart','height','hello','help','hide','high','hit','hold','hole','holiday','home','hope','horse','hospital','hotel','house','hour','hurry','husband','hurt',
             'ice','idea','if','increase','inside','iron','invite','island','it',
             'job','join','juice','jump',
             'keep','key','kill','kind','king','kitchen','knee','knife',
             'ladder','lady','land','laugh','lead','leave','leg','length','lesson','let','letter','library','lie','life','light','lip','list','listen','lock','long','look','love','low','luck',
             'machine','main','make','male','man','many','map','mark','market','matter','meal','meat','medicine','meet','member','mention','method','middle','milk','mind','minute','miss','mistake','mix','model','moment','money','month','morning','most','mother','mountain','mouth','move','music',
             'name','nation','nature','neck','net','news','newspaper','night','noise','north','nose','nothing','notice','number',
             'object','offer','office','oil','one','opposite','orange','order','other','outside','page','pain','paint','pair','paper','parent','park','part','partner','party','pass','past','path','pay','peace','pen','people','period','person','piano','pick','picture','piece','pin','place','plane','plant','plastic','plate','play','plenty','point','police','pool','position','possible','potato','power','present','press','price','private','prize','problem','produce','promise','public','pull','push','put',
             'queen','question','quiet',
             'radio','rain','raise','reach','read','record','red','remove','rent','repair','repeat','reply','report','rest','restaurant','result','return','rice','rich','ride','ring','rise','road','rock','room','round','rule','run','rush',
             'sad','safe','sail','salt','sand','save','school','science','search','seat','second','sell','sentence','serve','sex','shake','shape','share','she','shine','ship','shirt','shoe','shoot','shop','shoulder','show','sick','side','signal','silly','silver','simple','single','sing','sink','sister','size','skill','skin','skirt','sky','sleep','slip','smell','smile','smoke','snow','sock','soft','son','sound','soup','south','space','special','speed','spell','spend','sport','spread','spring','square','stand','star','start','station','stay','steal','step','still','stomach','stop','store','storm','story','street','structure','student','study','stupid','subject','substance','sugar','summer','sun','support','surprise','sweet','swim',
             'table','talk','taste','tea','teach','team','tear','telephone','television','tell','tennis','test','thing','tie','title','today','toe','tomorrow','tonight','tool','tooth','top','total','touch','town','train','travel','tree','trouble','trust','try','turn','type',
             'uncle','unit','use','usual',
             'vegetable','village','voice','visit',
             'wait','wake','walk','wash','watch','water','way','wear','weather','wedding','week','weight','welcome','west','wheel','while','white','wife','will','win','wind','window','wine','winter','wish','woman','wonder','word','work','world','worry',
             'yard','yesterday','you','young',
             'two'],
   nonNouns=['about','above','across','add','afraid','after','again','ago','agree','all','alone','along','already','always','am','an','and','angry','another','any','anyone','anytime','appear','are','around','arrive','as','at','aunt','autumn','away',
             'be','bean','behave','before','begin','behind','below','besides','best','better','between','bleed','boil','born','borrow','both','breathe','bright','bring','build','busy','but','by',
             'careful','careless','central','century','certain','chase','cheap','cheese','children','choose','circle','clever','clean','clear','climb','cloth','cloudy','close','coin','collect','colour','comb','compare','come','complete','continue','cool','copper','corn','correct','contain','cupboard',
             'dangerous','decide','decrease','deer','depend','destroy','develop','die','different','difficult','dirty','discover','do','down','dry','duck',
             'each','early','earn','easy','eight','either','electric','elephant','else','empty','enemy','enjoy','enough','enter','even','ever','every','everyone','exact','everybody','except','excited','expect','expensive','explain','extremely',
             'false','famous','far','fast','fever','find','fine','first','fit','five','flag','flat','float','flour','fool','for','foreign','forest','forget','forgive','fork','fox','four','free','freeze','fresh','friendly','from','full','furniture','further',
             'gentleman','get','goat','goodbye','grave','gray','grow','gun',
             'hammer','happen','happy','hard','have','he','healthy','hear','heaven','hen','her','here','hers','hill','him','his','hobby','hot','how','hundred','hungry',
             'i','important','in','into','introduce','invent','is','its',
             'jelly','just',
             'knock','know',
             'lamp','large','last','late','lately','lazy','leaf','learn','left','lend','less','like','lion','little','live','lonely','lose','lot','lower',
             'marry','may','me','mean','measure','million','modern','monkey','moon','more','much','must','my',
             'narrow','near','nearly','need','needle','neighbour','neither','never','new','next','nice','nine','no','noble','none','nor','not','now',
             'obey','ocean','of','off','often','old','on','only','open','or','our','out','over','own',
             'pan','pencil','pepper','per','perfect','petrol','photograph','pig','pink','please','pleased','pocket','poison','polite','poor','popular','pour','pretty','prevent','prince','prison','probably','proper','protect','provide','punish','pupil',
             'quick','quite',
             'rainy','ready','real','really','receive','remember','remind','right','rob','rubber','rude','ruler',
             'same','say','scissors','see','seem','send','seven','several','shade','shadow','sharp','sheep','sheet','shelf','short','should','shout','silence','similar','since','sit','six','slow','small','so','soap','some','someone','something','sometimes','soon','sorry','speak','spoon','stamp','steam','stone','strange','strong','successful','such','sudden','suitable','sunny','sure','sword',
             'take','tall','taxi','ten','terrible','than','that','the','their','then','there','therefore','these','thick','thin','think','third','this','though','threat','three','tidy','to','together','too','tram','true','twice',
             'ugly','under','understand','until','up','useful','usually',
             'very',
             'want','warm','was','waste','we','weak','were','well','wet','what','when','where','which','who','why','wide','wild','wire','wise','with','without',
             'yell','yet','your',
             'zero','zoo',
             'once'];

f=
s=>!/^([aouz]|th|..$)|e.+[ey]|[flo].r|a.p/.test(s)

//truthy:
tnoun = 0;
nouns.forEach(s=>tnoun += f(s));
console.log('Nouns: ' + tnoun + ' correct');

//falsy:
tnonNoun = 0;
nonNouns.forEach(s=>tnonNoun += !f(s));
console.log('Non-nouns: ' + tnonNoun + ' correct');
console.log('Total: ' + (tnoun + tnonNoun) + ' correct');
```

# Answer
> 11 votes
# Jelly, 48 bytes, score 731

This is my first ever answer in Jelly and I went to a lot of trouble putting this together. Ah well ... that was fun. :-)

```
O‘ḅ⁹%⁽€Oæ»4“Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’æ»Ḃ

```

*1 byte saved thanks to @JonathanAllan*

Try it online!

### Breakdown and test suites

* Non-nouns correctly identified as non-nouns: 265 / 414 (64%)
* Nouns correctly identified as nouns: 466 / 586 (79.5%)

### How?

We first compute a hash of the input string by:

* converting it to an integer by interpreting each code point as a base-256 digit
* applying modulo 4080 (chosen as the most efficient value with no more than 12 bits)
* keeping the 8 most significant bits of the result

This leaves us with an index in \[0 ... 255\] and thus divides all words into 256 groups.

For each group of words, we pre-compute a binary flag which is `1` if the group contains more nouns than non-nouns, and `0` otherwise. This leads to a 256-bit number ***N*** that we're going to use as a lookup-table. We store it as a base-250 encoded string.

Below is the binary representation of ***N***.

```
1000011000001011000101111011111001001101110010101101110010001101
0000010001101010010111110001110010010101110110110010111111010000
0001111010011110000110101011111000011110111011010011011110101100
1010010110101111000010101000101100000001110110100011111000101010

```

Which can be stored as `“Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’` in Jelly.

Hence the code:

```
O‘ḅ⁹%⁽€Oæ»4“Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’æ»Ḃ    main link

O                                                   convert the input string to a list of
                                                    code points
 ‘                                                  increment each of them
  ḅ⁹                                                convert from base 256 to an integer
    %⁽€O                                            modulo 4080
        æ»4                                         drop the 4 least significant bits
           “Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’æ»     right shift N by this amount
                                               Ḃ    test the least significant bit

```

# Answer
> 10 votes
# Jelly, 50 bytes, score 763

Using a hash now (much like Arnauld's Jelly answer)

```
OP%⁽Wpị“!ḋGẠ⁻Ṭȥʋt|Ḥ\⁾°½İ@G2ḂƑ½ịʂ¶ɦḲ⁷³Hz~⁵p9)⁹ƙ¿’B¤

```

**Try It Online!**

250 / 414 for Non-Nouns
513 / 586 for Nouns
Total = 250 + 513 = 763.

### How?

Builds a table with 308 entries, either 1 (identifying a noun) or 0 (identifying a non noun) and indexes into it using a key provided by a hash function that utilises the product of the ordinals of the input word:

```
OP%⁽Wpị“!ḋGẠ⁻Ṭȥʋt|Ḥ\⁾°½İ@G2ḂƑ½ịʂ¶ɦḲ⁷³Hz~⁵p9)⁹ƙ¿’B¤ - Link: list of characters, word
O                                                  - convert to ordinals
 P                                                 - product
   ⁽Wp                                             - base 250 number = 22863
  %                                                - modulo (by 22863)
                                                 ¤ - nilad plus link(s) as a nilad:
       “!ḋGẠ⁻Ṭȥʋt|Ḥ\⁾°½İ@G2ḂƑ½ịʂ¶ɦḲ⁷³Hz~⁵p9)⁹ƙ¿’   -   base 250 number
                                                B  -   as a binary list (308 bits)
      ị                                            - index into (1-indexed and modular,
                                                  -   so adds another modulo by 308)

```

---

### Previous:  ~~50~~  47 bytes, score 684

```
ḣ3Ẇf“QṘ°ḂżÐŒ#ḍæ09»s2¤Ȧ¬ȧØY⁾niyṖf⁽ż2ị$
0,-2ịE¬ȧÇ

```

A monadic link taking a word and returning a list of one character (truthy) if the word is identified as a noun, or an empty list or zero (both falsey) if it is not.

**Try it online!** (the footer performs an if else on the result to print `Noun` or `Non-Noun`)
...or see the scoring program (counts up truthy indexes across the two lists and then calculates the score).

Score breakdown: 462 / 586 nouns correctly identified (124 incorrect), 222 / 414 non-nouns correctly identified (192 incorrect) -- total correct = 684 / 1000.

### How?

Guess it is not a noun if...

* the last character and the character two before that are equal (with modular and 1-based indexing)
* either of the first two length 2 substrings are in:
`'be', 'th', 'le', 'he', 'm ', 'ev', 'et', 's ', 'fl', 'ax', 'en', 'fo', 'am', 'az'` (note: `'m '` and `'s '` are only here to ease compression, but they never appear anyway)
* The -299th index (with modular and 1-based indexing) is any of:
`aenouyz` (although this is implemented inversely and with excess capital letters)
...since the words all have length between 1 and 11 the -299th index is equivalent to using the length to index mapping: `{7:2; 8:5; 9:7; 11:9; else 1}`

```
ḣ3Ẇf“QṘ°ḂżÐŒ#ḍæ09»s2¤Ȧ¬ȧØY⁾niyṖf⁽ż2ị$ - Link 1: list of characters, word
ḣ3                                    - head to index 3 (1st 3 characters, like 'abc')
  Ẇ                                   - all sublists (['a','b','c','ab','bc','abc']
                    ¤                 - nilad followed by link(s) as a nilad:
    “QṘ°ḂżÐŒ#ḍæ09»                    - compression of "bethlehem evets flaxenfoamaz"
                  s2                  - split into chunks of 2:
                                      -   be,th,le,he,m ,ev,et,s ,fl,ax,en,fo,am,az
   f                                  - filter keep (can only match 'ab' or 'bc')
                     Ȧ                - any and all (0 if empty, 1 if not)
                      ¬               - logical not
                        ØY            - consonant -y yield = "BCD...WXZbcd...wxz"
                          ⁾ni         - character pair = "ni" (no shrubbery for you!)
                             y        - translate (exchange the n for an i)
                              Ṗ       - pop (remove the z)
                       ȧ              - logical and
                                    $ - last two links as a monad:
                                ⁽ż2   -   base 250 literal = -299
                                   ị  -   index into the word
                               f      - filter keep

0,-2ịE¬ȧÇ - Main link: list of characters, word
0,-2      - pair zero with -2 = [0,-2]
    ị     - index into the word (last character and the one before the one before that)
     E    - all (both) equal?
      ¬   - logical not
        Ç - call the last link (1) as a monad
       ȧ  - logical and

```

---

13 bytes, score: 638

A first quick bash (extended above)

```
ØY⁾niyṖf⁽ż2ị$

```

# Answer
> 2 votes
# Julia 34bytes, 609

`f(w)=hash(w)&0x0800000000004808>0`

I wanted to save on characters by using the in-built hash. I feel like there must be a way to do this better. Julia is just not friendly enough with the bit-banging operations I want to use to make this better I think.

Finding suitable bitmasks for the hash to separate them, is an interesting game.

# Answer
> 2 votes
# Python 2, 50 bytes, accuracy: 596

```
lambda x:2<len(x)<7 or x[0]in"abcgmprs"or"st" in x

```

Try it online!

Simply checks first letter, length, and whether "st" is in the word Code assumes that word is defined as x (Edit: Thanks to issacg for fixing code from snippet to function)

# Answer
> 2 votes
## Haskell, 36 bytes, ~~626~~ 631

```
f x=length x>2&&x!!0`notElem`"aenou"

```

# Answer
> 1 votes
# Python 3, 50 bytes, score 602

Python isn't the most verbose language, but 50 bytes is tough.

```
lambda x:all(x.count(y)<1for y in["ful","y","er"])

```

---
Tags: code-challenge, decision-problem, natural-language, test-battery
---


# Question
Title: Codegolf the sequence of distance-3 Hamming Codewords (A075926)
Codegolf the hamming code (with distance equals 3)!

The sequence looks like this: 0, 7, 25, 30, 42, 45, 51, 52, 75, 76, 82, 85, 97, 102, 120, 127, 385, 390, 408, 415, 427, 428, 434, 437, 458, 461, 467, 468, 480, 487, 505, 510, 642, 645, 667, 668, 680...

## Task

Given `n` output the first `n` items in OEIS sequence A075926. Your program should work for any integer `n` where `0 <= n < 2^15`. This sequence is known as the sequence of hamming codewords with distance being 3.

**Rules:**

* Post both an ungolfed version of your code (or an explatation), and the golfed version, so that other people can understand how it works
* If your program is written in a language with a compiler, specify which compiler and the compiler settings you used. Non-standard language features are allowed as long as it compiles with the compiler you specified, and the compiler was created prior to this question

**Sequence Definition:** Given a distance 3 hamming codeword `k`, the variants of `k` are `k` itself, and any nonnegative integer that can be produced by flipping one of `k`'s bits. The `n`th hamming codeword is the smallest nonnegative integer that doesn't share a variant with any preceeding distance 3 hamming codeword. Here are the first twenty d-3 hamming codewords in binary:

> 0, 111, 11001, 11110, 101010, 101101, 110011, 110100, 1001011, 1001100, 1010010, 1010101, 1100001, 1100110, 1111000, 1111111, 110000001, 110000110, 110011000, 110011111, 110101011

**Ungolfed C++ code to produce sequence:**

```
//Flips the nth bit
size_t flipN(size_t val, int bit) {
    return val ^ (1ull << bit);
}
void Hamming(size_t n) {
    int bits_to_use = 20;
    //This vector keeps track of which numbers are crossed off
    //As either hamming codewords or their variants.
    std::vector<bool> vect(1ull << bits_to_use, false);
    size_t pos = 0;
    size_t val = 0;
    while(val <= n) {
        //Checks to see that pos hasn't been crossed off
        if(vect[pos]) goto loopend;
        for(int i=0; i < bits_to_use; ++i)
        {
            if(vect[flipN(pos, i)]) goto loopend;
            //Checks to see that none of the variants
            //of pos have been crossed off
        }
        //If both those conditions are satisfied, output pos
        //As the next hamming codeword
        cout << pos << endl;
        //Here we cross off all the variants
        vect[pos] = true;
        for(int i=0; i < bits_to_use; ++i)
        {
            vect[flipN(pos, i)] = true;
        }
        ++val;
        loopend:
        ++pos;
    }
}

```

# Answer
# Python 2, ~~98~~ 97 bytes

<sup>-1 byte thanks to Mr. Xcoder</sup>

```
x=input()
l=[]
i=0
while len(l)<x:s=any(bin(i^n).count('1')<3for n in l);i+=s;l+=[i]*-~-s
print l

```

Try it online!

Straightforward implementation, using `xor` to calculate the hamming distance.
The inner loop is equivalent to :

```
if any(bin(i^n).count('1')<3 for n in l):
   i+=1
else:
   l.append(i)

```
> 2 votes

# Answer
# Pyth, ~~34 21~~ 19 bytes

*Special Thanks to @LeakyNun for golfing off **half of my solution!***

```
u+Gf.Am<2sjxdT2G0QY

```

**Try it here** or **Check out the test Suite**.

---

Alternative, 19-byte solutions (Try one here):

```
u+Gf-Zm<2sjxdT2GZQY
u+Gf-0m<2sjxdT2G0QY
u+Gf.Am<2sjxdT2GZQY

```
> 2 votes

---
Tags: code-golf, number, sequence, error-correction
---


title: Real base conversion

text:
# Question
Title: Real base conversion
We've had a few challenges for base conversion, but all of them seem to apply to integer values. Let's do it with real numbers!

# The challenge

Inputs:

* A real **positive number** *x*, expressed in base 10. This can be taken as a double-precision float or as a string. To avoid precision issues, the number can be assumed to be greater than 10−6 and less than 1015.
* A **target base** *b*. This will be an integer from 2 to 36.
* A **number of fractional digits** *n*. This will be an integer from 1 to 20.

Output: the **representation** of *x* in base *b* with *n* fractional digits.

When computing the output expression, the digits beyond the *n*-th should be **truncated** (not rounded). For example, `x = 3.141592653589793` in base `b = 3` is `10.0102110122...`, so for `n = 3` the output would be `10.010` (truncation), not `10.011` (rounding).

For *x* and *b* that produce a finite number of digits in the fractional part, the **equivalent infinite representation** (truncated to *n* digits) is also allowed. For example, `4.5` in decimal can also be represented as `4.49999...`.

Don't worry about **floating point errors**.

# Input and output format

*x* will be given without leading zeros. If *x* happens to be an integer you can assume that it will be given with a zero decimal part (`3.0`), or without decimal part (`3`).

The output is flexible. For example, it can be:

* A string representing the number with a suitable separator (decimal point) between integer and fractional parts. Digits `11`, `12` etc (for *b* beyond 10) can be represented as letters `A`, `B` as usual, or as any other distinct characters (please specify).
* A string for the integer part and another string for the fractional part.
* Two arrays/lists, one for each part, containing numbers from `0` to `35` as digits.

The only restrictions are that the integer and fractional parts **can be told apart** (suitable separator) and use the **same format** (for example, no `[5, 11]` for the list representing the integer part and `['5', 'B']` for the list representing the fractional part).

# Additional rules

# Test cases

Output is shown as a string with digits `0`, ..., `9`, `A`, ... , `Z`, using `.` as decimal separator.

```
x, b, n                    ->  output(s)

4.5, 10, 5                 ->  4.50000 or 4.49999
42, 13, 1                  ->  33.0 or 32.C
3.141592653589793, 3, 8    ->  10.01021101
3.141592653589793, 5, 10   ->  3.0323221430
1.234, 16, 12              ->  1.3BE76C8B4395
10.5, 2, 8                 ->  1010.10000000 or 1010.01111111
10.5, 3, 8                 ->  101.11111111
6.5817645, 20, 10          ->  6.BCE2680000 or 6.BCE267JJJJ
0.367879441171442, 25, 10  ->  0.94N2MGH7G8
12944892982609, 29, 9      ->  PPCGROCKS.000000000

```

# Answer
> 1 votes
# Jelly, 16 bytes

```
*×⁵b⁸ḞðṖḣ⁹,ṫø⁹N‘

```

Try it online!

Note that singletons are printed as the element in the output.

# Answer
> 7 votes
## JavaScript (ES8), ~~81~~ ~~74~~ 71 bytes

```
f=
(x,b,n,g=x=>x.toString(b))=>g(x-x%1)+'.'+g(x%1).substr(2,n).padEnd(n,0)
```

```
<div oninput=o.textContent=f(+x.value,b.value,n.value)><input id=x><input type=number min=2 max=36 value=10 id=b><input type=number min=1 max=20 value=10 id=n><pre id=o>
```

Works for `x` between `1e-6` and `1e21`, `b` from `2` to `36` (exactly as required) and `n` from `1` to anything from `10` to `48` depending on the base before floating-point errors creep in. Edit: Saved 7 bytes with help from @Birjolaxew. Saved a further 3 bytes with help from @tsh. Previous 74-byte version also worked with negative numbers:

```
f=
(x,b,n,[i,d]=`${x.toString(b)}.`.split`.`)=>i+`.`+d.slice(0,n).padEnd(n,0)
```

```
<div oninput=o.textContent=f(+x.value,b.value,n.value)><input id=x><input type=number min=2 max=36 value=10 id=b><input type=number min=1 max=20 value=10 id=n><pre id=o>
```

# Answer
> 5 votes
# Python 2, ~~153~~ ~~149~~ ~~144~~ ~~137~~ ~~135~~ 109 bytes

```
def f(x,b,m):
 i=int(x);s=[];t=[]
 while i:s=[i%b]+s;i/=b
 while m:m-=1;x=x%1*b;t+=[int(x)]
 return s or[0],t

```

Hadn't noticed I can just return the digits as numbers, so that makes it a lot simpler. Returns two lists of digits, first for the integer part, second for the fractional.

Try it online!

# Answer
> 5 votes
# Perl 6, 25 bytes

```
->\x,\b,\n{+x .base(b,n)}

```

Try it

## Expanded:

```
-> \x, \b, \n {
  +x            # make sure it is a Numeric
  .base( b, n ) # do the base conversion
}

```

Note that the space is so that it is parsed as `(+x).base(b,n)`
not `+( x.base(b,n) )`.

# Answer
> 4 votes
# Ruby, 45 bytes

```
->x,b,n{(x*b**n).round.to_s(b).insert(~n,?.)}

```

### Why?

Since b^n in base b is 10^n, we multiply x by that number, and then add the decimal point where it belongs.

Try it online!

# Answer
> 3 votes
# Mathematica, 158 bytes

since this challenge allready got a very nice answer in mathematica by @KellyLowder, I tried to produce (with a different approach) **the exact results as shown in the test cases**

```
ToUpperCase[""<>Insert[StringReplace[ToString@BaseForm[#,p]&/@PadRight[#&@@(d=RealDigits[#,p=#2]),w=(#3+d[[2]])][[;;w]],"\n "<>ToString@p->""],".",d[[2]]+1]]&

```

**input**

> \[12944892982609, 29, 9\]

**output**

> PPCGROCKS.000000000

# Answer
> 3 votes
# C (gcc), ~~157~~ 152 bytes

Needs 64 bits `long int` for this to work with larger test cases.

*-5 bytes thanks to Peter Cordes*

```
#define P r=99;i=l=x;do{z[--r]=48+7*(l%b>9)+l%b;}while(l/=b);printf(z+r)
long i,r,l;char z[99];f(x,b,n)double x;{P;putchar(46);while(n--){x=(x-i)*b;P;}}

```

Try it online!

edit: a few bytes can be shaved if it's allowed to output two strings separated by a newline separator:

## 149 bytes:

```
#define P r=99;i=l=x;do{z[--r]=48+7*(l%b>9)+l%b;}while(l/=b);printf(z+r)
long i,r,l;char z[99];f(x,b,n)double x;{P;puts("");while(n--){x=(x-i)*b;P;}}

```

edit: this submission is not the longest one, yay!

# Answer
> 2 votes
# SageMath, 68 bytes

```
def f(n,b,k):y=n.str(b).split('.')+[''];return y[0],(y[1]+'0'*k)[:k]

```

Try it online!

# Answer
> 2 votes
## Mathematica 47 Bytes

```
TakeDrop@@r[#,#2,#3+Last@(r=RealDigits)[#,#2]]&

```

Calling `RealDigits` twice to first figure out the number of digits to the left of the decimal.

# Answer
> 1 votes
# Haskell, 188 bytes

```
f=fromIntegral
g 0 _=[]
g n p=g(div n p)p++[mod n p]
z=(!!)(['0'..'9']++['A'..'Z']++['.'])
h x p l|(i,d)<-properFraction x=z<$>(g i p++[36]++(last$g(floor$d*(f p**f l))p:[0<$[1..l]|d==0]))

```

Try it online!

`g` converts a number to a list representing that number in a given base

`z` maps integers to letters (`36 = .`)

`h` applies the previous functions to the integer and fractional part of a number.

# Answer
> 1 votes
# Axiom, 127 bytes

```
g(a)==floor(a)::INT;f(a:Float,b:PI,n:NNI):Any==(b<2 or n>28=>%i;x:=g(a);radix(x,b)+radix(g((a-x)*b^n),b)::RadixExpansion b/b^n)

```

results

```
(4) -> f(%e,2,10)
   (4)  10.1011011111
                                                   Type: RadixExpansion 2
(5) -> f(%e,3,10)
   (5)  2.2011011212
                                                   Type: RadixExpansion 3
(6) -> f(%e,35,10)
   (6)  2.P4VBNEB51S
                                                  Type: RadixExpansion 35
(7) -> f(1.4,35,10)
   (7)  1.DYYYYYYYYY
                                                  Type: RadixExpansion 35
(8) -> f(%pi,3,8)
   (8)  10.01021101
                                                   Type: RadixExpansion 3
(9) -> f(%pi,5,10)
   (9)  3.032322143
                                                   Type: RadixExpansion 5
(10) -> f(1.234,16,12)
   (10)  1.3BE76C8B4395
                                                  Type: RadixExpansion 16

```

It has a little problem for final zero example

```
 f(4.5,10,5)

```

Would return '4.5' and not '4.50000'

# Answer
> 1 votes
# Axiom, 566 bytes

```
c:=alphanumeric()::List Character
f(a:INT,b:PI):List Character==(r:=[];repeat(y:=a rem b;r:=cons(c.(y+1),r);a:=a quo b;a=0=>break);r)
g(x)==floor(x)::INT
F(x)==>for i in 1..#x repeat z:=concat(z,x.i)
w(a:Float,b:PI,n:NNI):String==
  z:="";b<2 or b>36 or a<0=>z
  ip:=g(a);    fp:=g((a-ip)*b^n)
  ipb:=f(ip,b);fpb:=f(fp,b);cnt:=n-#fpb
  for i in 1..cnt repeat fpb:=cons(c.1,fpb)
  F(ipb);z:=concat(z,".");F(fpb)
  z

h(a,b,n)==>(n>=0 and b>0=>(nd123:=10+g(n*log_2(b)/log_2(10));mxv123456:=digits(nd123::PI);res78484:=w(a,b,n);digits(mxv123456);res78484);"")

```

it was particular difficult this question; afther some time in write something, the right results it seems generate using one macro for preserve digits()... it is not golfed too much...results:

```
(7) -> h(4.5,10,5)
   (7)  "4.50000"
                                                             Type: String
(8) -> h(42,13,1)
   (8)  "33.0"
                                                             Type: String
(9) -> h(%pi,3,8)
   (9)  "10.01021101"
                                                             Type: String
(10) -> h(%pi,5,10)
   (10)  "3.0323221430"
                                                             Type: String
(11) -> h(1.234,16,12)
   (11)  "1.3BE76C8B4395"
                                                             Type: String
(12) -> h(0.367879441171442,25,10)
   (12)  "0.94N2MGH7G8"
                                                             Type: String
(13) -> h(12944892982609,29,9)
   (13)  "PPCGROCKS.000000000"
                                                             Type: String
(14) -> h(6.5817645,20,10)
   (14)  "6.BCE267JJJJ"
                                                             Type: String

```

the real target is one function that convert to base 2..36 each Float \[that has k:=digits()\] or each calculated number as %pi or %e or the division of two float/int as in 1./3. \['oo' digits\]

```
(15) -> h(%pi,13,800)
   (15)
  "3.1AC1049052A2C77369C0BB89CC9883278298358B370160306133CA5ACBA57614B65B410020
  C22B4C71457A955A5155B04A6CB6CC2C494843A8BBBBA9A039B77B34CB0C036CAC761129B3168
  B8BAB860134C419787C911812985646C7AAA3025BAA118B3AB8265CB347852065667291482145
  6C533447BC53A5262177C9985455C395626091A2CC3126B395C91B65B654A1804226197528410
  29A8A4A55CC7937B347B77B5A914127B11C6A57A84510775A9A467819A468B6B74339CC1290B2
  24921C6A771BC2AB6AB41735119C2231545A86399483119AAA5AC34B46B7B5C9089946A364860
  9B26CB0BAC0ABCBA182C12881933AA93C3942C71AA664753989A3C82166BA2109796C4A134607
  59725A72C9117AC980556A147557C319438287226C94725B125753B009387A48AA45CB1960A04
  A064052C00A6069371949872B14590895C555CB01A39B7589824B8621618A8B1971841201A2AB
  B04B80C7534CC1CB079581491995B46C679555316288C82665645A1A600C1A669B865651B6B842470C018B03C1115B3C4306C015C0B45C"
                                                             Type: String

```

---
Tags: code-golf, math, number, arithmetic, base-conversion
---


title: Unrestricted Languages

text:
# Question
Title: Unrestricted Languages
One of my favorite types of challenges on this site are challenges. These challenges impose a computer tractable restriction that the sources of potential answers must pass. I like these challenges so much I have been working on a golfing language designed to win at these challenges for some time now. Now I want to extend the challenge to you. Your task is to design a language to solve a variety of restricted source tasks. You will time to design and implement a language, at which point changes and new additions will be non-competing and all of the submissions will go head to head in a gauntlet of challenges.

## Scoring

Before the challenge is posted I will come up with a list of simple challenges to solve and a list of source restrictions to follow. For each matching of challenge and source restrictions your language can earn between 0 and 2 points. (there will be 10 challenges and 10 restrictions leading to 100 total combinations) A language scores

* 1 point if it can complete the task with the restriction in under 150 bytes
* 2 points if the solution is the shortest solution of any language competing (both languages will score 2 points in the event of a tie)
* 0 points if they are unable to create a program that completes the task under the restriction in less than 150 bytes.

Your score will be the sum of all points earned in every possible match up. The goal is to get the highest score. Other people may help you to golf your solutions to each challenge and improve your score.

I will reveal 4 items of each list at the time of posting and an additional 8 one week after the second answer. You will only be allowed to score 1 point (shortest submission does not count) in any matching that has both parts revealed before the the first week. This way you can get an idea of how well your language stacks up while you are working on it, but you can't design you language simply to build in all of the challenges and restrictions.

I will include a hash of the intended categories with the question so you can be sure I do not change them during the week to advantage any party. In addition I will not tell anyone the hidden parameters until the week is up nor compete in the challenge myself.

### Pre-existing languages

This challenge is open to all pre-existing languages however if you are not the author of the language, please make your answer a community wiki so that other members of our community can contribute to the score directly. Command line flags need not obey any restrictions however every program should be run with the same command line arguments (i.e. you should pick one and stick with it). These do not add to your byte count.

## Challenges and restrictions

Restrictions are enforced on the ASCII encoding of your binaries regardless of the code-page you use. Some of these link to an existing question on the site from which they inherit their io requirements for challenges and source restrictions for restrictions. You can ignore anything "banning builtins" or overriding existing meta consensuses on any of the linked challenges.

As a word of warning: do not try to rule lawyer; I know it is a competition but because there are essentially 100 different sub-challenges challenges and I simply cannot guarantee that all of them will be entirely unproblematic. Just try to have fun.

### Challenges

### Restrictions

The remaining criteria have a sha512 hash of:

```
4de5eca33c6270798606cf1412820c4ce112d8b927ef02877f36795b2b15ffacca51ea598fa89b8d6bc9f4cde53810e0e7ade30e536e52e28f40a6a13841dfc5  -

```

# Answer
> 6 votes
# Width

The interpreter is still a work in progress (I have several unused command slots still). The repo, with more documentation, can be found here.

Dennis added Width to TIO less than a minute ago: Try It Online!

Width is an esoteric stack-based language I developed recently based on ideas I first dumped in this question. It is based entirely on how wide, more or less, a letter is in a "regular" font. The only characters that do anything are letters, uppercase and lowercase. All other characters are ignored. I split letters up into 10 different width categories, which form the 10 different actions possible in Width:

```
0: i j l                     # do while counter > 0
1: f r t I                   # end
2: c k s v x y z J           # 0 in commands
3: a b d e g h n o p q u L   # separator (no-op)
4: F T Z                     # push base 10 number, using left side row titles (width numbers); terminated with original char
5: A B E K P S V X Y         # 1 in commands
6: w C D H N R U             # 2 in commands
7: G O Q                     # push string literal; sets of 2 width numbers equate to index in printable ASCII; terminated with original char
8: m M                       # if top of stack
9: W                         # else

```

`2`, `5`, and `6` provide access to the commands, most of which interact with the stack. More information can be found at the `info.txt` page in the Github repo.

This is the Python code of the interpreter. I still have several commands to add, and I'm considering how to work with error-handling, but otherwise it should be complete. (I'm also going to add a flag at some point to allow testing with a more abstract syntax, because otherwise this language is a giant pain to work with)

```
import sys
import math
import numbers
import functools

try:
    file = sys.argv[1]
except IndexError:
    file = "source.wide"

with open(file) as f:
    source = f.read()

translation = ("ijl", "frtI", "cksvxyzJ", "abdeghnopquL", "FTZ", "ABEKPSVXY", "wCDHNRU", "GOQ", "mM", "W")
chars = "".join(sorted("".join(translation)))
strings = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n\t"""

def trans(letter):
    for each in translation:
        if letter in each:
            return translation.index(each)

COMMAND = "COMMAND"
COMMANDS = (2, 5, 6)
NUMBER = "NUMBER"
STRING = "STRING"
DO = "DO"
IF = "IF"
ELSE = "ELSE"
END = "END"
SEPARATOR = "SEPARATOR"

class Token:
    def __init__(self, val, type_):
        self.val = val
        self.type = type_

class Lexer:
    def __init__(self, src):
        self.src = src
        self.pos = 0
        self.char = self.src[self.pos]

    def read(self):
        if self.char is None:
            return None

        command = trans(self.char)

        if command == 0:
            self.advance()
            return Token(0, DO)
        elif command == 1:
            self.advance()
            return Token(1, END)
        elif command == 3:
            self.advance()
            return Token(3, SEPARATOR)
        elif command == 4:
            return self.read_num()
        elif command == 7:
            return self.read_str()
        elif command == 8:
            self.advance()
            return Token(8, IF)
        elif command == 9:
            self.advance()
            return Token(9, ELSE)
        else:
            return self.read_cmd()

    def advance(self):
        self.pos += 1

        try:
            self.char = self.src[self.pos]
        except IndexError:
            self.char = None

    def read_num(self):
        delim = self.char
        self.advance()

        res = ""
        while self.char is not None and self.char != delim:
            res += str(trans(self.char))
            self.advance()

        self.advance()

        return Token(int(res), NUMBER)

    def read_str(self):
        def read_char():
            res_ = str(trans(self.char))
            self.advance()
            res_ += str(trans(self.char))
            self.advance()
            try:
                return strings[int(res_)]
            except IndexError:
                return " "

        delim = self.char
        self.advance()

        res = ""
        while self.char is not None and self.char != delim:
            res += read_char()

        self.advance()

        return Token(res, STRING)

    def read_cmd(self):
        command = ""
        while self.char is not None and trans(self.char) in COMMANDS and len(command) <= 4:
            command += str(COMMANDS.index(trans(self.char)))
            self.advance()

        return Token(command, COMMAND)

source = "".join(filter(lambda c: c in chars, source))

stack = []
backburner = []
counter = 0

def set_counter(val):
    global counter
    counter = int(val)

    if counter < 0:
        counter = 0

def set_stack(val):
    global stack
    stack = val

def num_input():
    inp = input()
    try:
        stack.append(int(inp))
    except ValueError:
        try:
            stack.append(float(inp))
        except ValueError:
            pass

def flip_ends():
    if len(stack) > 1:
        stack[0], stack[-1] = stack[-1], stack[0]

def clear_stack():
    global stack
    stack = []

def reload_stack(is_top):
    global backburner, stack

    if is_top:
        stack.extend(backburner)
    else:
        stack = backburner + stack

    backburner = []

# https://stackoverflow.com/a/15285588/7605753
def is_prime(n):
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    if n < 9:
        return True
    if n % 3 == 0:
        return False
    r = int(math.sqrt(n))
    _f = 5
    while _f <= r:
        if n % _f == 0:
            return False
        if n % (_f + 2) == 0:
            return False
        _f += 6
    return True

def error():
    raise Exception

commands = {
    "0": lambda: stack.append(stack[-1]),
    "1": lambda: stack.append(stack.pop(-2)),
    "2": lambda: stack.pop(),
    "00": lambda: set_counter(stack[-1]),
    "01": lambda: stack.append(len(stack)),
    "02": lambda: stack.append(input()),
    "10": num_input,
    "11": lambda: stack.append(str(stack.pop())),
    "12": lambda: stack.append(int(stack.pop())),
    "20": lambda: set_counter(counter + 1),
    "21": lambda: set_counter(counter - 1),
    "22": lambda: print(stack.pop()),
    "000": lambda: stack.append(float(stack.pop())),
    "001": lambda: stack.append(-stack.pop()),
    "002": lambda: stack.append(not stack.pop()),
    "010": lambda: stack.append(stack.pop(-2) + stack.pop()),
    "011": lambda: stack.append(stack.pop(-2) - stack.pop()),
    "012": lambda: stack.append(stack.pop(-2) / stack.pop()),
    "020": lambda: stack.append(stack.pop(-2) // stack.pop()),
    "021": lambda: stack.append(stack.pop(-2) * stack.pop()),
    "022": lambda: stack.append(stack.pop(-2) % stack.pop()),
    "100": lambda: stack.append(math.factorial(stack.pop())),
    "101": lambda: stack.append(str(stack.pop(-2)) + str(stack.pop())),
    "102": lambda: stack.append(math.pow(stack.pop(-2), stack.pop())),
    "110": lambda: stack.append(math.sqrt(stack.pop())),
    "111": lambda: stack.append(math.log(stack.pop(-2), stack.pop())),
    "112": lambda: stack.append(~stack.pop()),
    "120": lambda: stack.append(stack.pop(-2) | stack.pop()),
    "121": lambda: stack.append(stack.pop(-2) & stack.pop()),
    "122": lambda: stack.append(stack.pop(-2) << stack.pop()),
    "200": lambda: stack.append(stack.pop(-2) >> stack.pop()),
    "201": lambda: stack.append(stack.pop(-2)[stack.pop()]),
    "202": lambda: stack.append(str(stack.pop(-2)) * stack.pop()),
    "210": lambda: stack.append(counter),
    "211": lambda: set_counter(stack.pop()),
    "212": lambda: stack.extend(list(str(stack.pop()))),
    "220": flip_ends,
    "221": lambda: stack.append(len(stack[-1])),
    "222": lambda: print(stack[-1]),
    "0000": lambda: stack.reverse(),
    "0001": lambda: stack.sort(),
    "0002": lambda: stack.append(stack[counter]),
    "0010": lambda: stack.append(stack[stack.pop()]),
    "0011": 0,
    "0012": 0,
    "0020": lambda: stack.append(sum(n for n in stack if isinstance(n, numbers.Number))),
    "0021": lambda: stack.append(functools.reduce(lambda x, y: x*y, [n for n in stack if isinstance(n, numbers.Number)], 1)),
    "0022": 0,
    "0100": lambda: (backburner.extend(stack), clear_stack()),
    "0101": lambda: reload_stack(True),
    "0102": lambda: reload_stack(False),
    "0110": lambda: backburner.append(stack.pop()),
    "0111": lambda: backburner.append(list(stack.pop())),
    "0112": lambda: stack.pop().split(stack.pop()),
    "0120": lambda: stack.append(backburner[-1]),
    "0121": lambda: (lambda depth=stack.pop(): (set_stack(stack[-depth:]), backburner.append(stack[:depth])))(),
    "0122": lambda: (lambda depth=stack.pop(): (set_stack(stack[:-depth]), backburner.append(stack[depth:])))(),
    "0200": lambda: set_stack([stack.pop().join(stack)]),
    "0201": lambda: set_stack(["".join(stack)]),
    "0202": lambda: (lambda depth=stack.pop(-2): set_stack(stack[-depth:] + [stack.pop().join(stack[:depth])]))(),
    "0210": lambda: (lambda depth=stack.pop(): set_stack(stack[-depth:] + ["".join(stack[:depth])]))(),
    "0211": 0,
    "0212": 0,
    "0220": lambda: stack.append(stack.pop().split(stack.pop())),
    "0221": lambda: stack.append(stack.pop().split(", ")),
    "0222": 0,
    "1000": lambda: stack.append(is_prime(stack[-1])),
    "1001": lambda: stack.append((lambda s=stack.pop(): s == s[::-1])()),
    "1002": lambda: stack.append(1 / stack.pop()),
    "1010": lambda: stack.append(stack.pop() - 1),
    "1011": lambda: stack.append(stack.pop() + 1),
    "1012": lambda: stack.append(stack.pop() * 2),
    "1020": lambda: stack.append(stack.pop() / 2),
    "1021": lambda: stack.append(stack.pop() ** 2),
    "1022": lambda: float("." + str(stack.pop())),
    "1100": lambda: stack.append(stack.pop() == stack.pop()),
    "1101": lambda: stack.append(stack.pop() != stack.pop()),
    "1102": lambda: stack.append(stack.pop() > stack.pop()),
    "1110": lambda: stack.append(stack.pop() < stack.pop()),
    "1111": lambda: stack.append(stack.pop() >= stack.pop()),
    "1112": lambda: stack.append(stack.pop() <= stack.pop()),
    "1120": lambda: stack.append(stack.pop() in stack),
    "1121": lambda: stack.append(stack.pop() in backburner),
    "1122": lambda: stack.append(stack.pop() == counter),
    "1200": lambda: stack.append(stack.pop() in stack.pop()),
    "1201": lambda: stack.append(stack.pop(-2).find(stack.pop())),
    "1202": 0,
    "1210": 0,
    "1211": 0,
    "1212": lambda: stack.append(stack.pop().lower()),
    "1220": lambda: stack.append(stack.pop().upper()),
    "1221": lambda: stack.append(ord(stack.pop())),
    "1222": lambda: stack.append(chr(stack.pop())),
    "2000": lambda: stack.append(math.floor(stack.pop())),
    "2001": lambda: stack.append(math.ceil(stack.pop())),
    "2002": lambda: stack.append(round(stack.pop())),
    "2010": lambda: stack.append(abs(stack.pop())),
    "2011": 0,
    "2012": 0,
    "2020": lambda: stack.append(len(stack.pop())),
    "2021": 0,
    "2022": 0,
    "2100": lambda: stack.append(min(stack)),
    "2101": lambda: stack.append(max(stack)),
    "2102": lambda: stack.append(stack.count(stack.pop())),
    "2110": lambda: stack.append(sum(stack) / len(stack)),
    "2111": 0,
    "2112": 0,
    "2120": 0,
    "2121": 0,
    "2122": 0,
    "2200": lambda: stack.append(stack.pop(-3).replace(stack.pop(-2), stack.pop())),
    "2201": lambda: stack.append(stack.pop(-3).replace(stack.pop(-2), stack.pop(), 1)),
    "2202": lambda: stack.append(stack.pop(-2).replace(stack.pop(), "")),
    "2210": lambda: stack.append(stack.pop(-2).replace(stack.pop(), "", 1)),
    "2211": 0,
    "2212": lambda: stack.append(eval(stack.pop())),
    "2220": lambda: stack.append(eval(input())),
    "2221": lambda: print(stack[-1]),
    "2222": lambda: error()
}

def run_cmd(name):
    global stack, counter, backburner

    state = {
        "stack": list(stack),
        "counter": counter,
        "backburner": list(backburner)
    }

    # TODO: unknown command

    try:
        commands[name]()
    except IndexError:
        stack = state["stack"]
        counter = state["counter"]
        backburner = state["backburner"]

class AST:
    pass

class Main(AST):
    def __init__(self):
        self.nodes = []

class Do(AST):
    def __init__(self, node):
        self.node = node

class If(AST):
    def __init__(self, first, second):
        self.first = first
        self.second = second

class Literal(AST):
    def __init__(self, val):
        self.val = val

class Command(AST):
    def __init__(self, val):
        self.val = val

class Parser:
    def __init__(self, lexer):
        self.lexer = lexer
        self.token = None

    def parse(self):
        pgm = Main()
        self.token = self.lexer.read()

        while self.token is not None and self.token.type != END and self.token.type != ELSE:
            if self.token.type == DO:
                pgm.nodes.append(Do(self.parse()))

            elif self.token.type == NUMBER or self.token.type == STRING:
                pgm.nodes.append(Literal(self.token.val))

            elif self.token.type == IF:
                first = self.parse()

                if self.token.type == ELSE:
                    second = self.parse()
                else:
                    second = None

                pgm.nodes.append(If(first, second))

            elif self.token.type == COMMAND:
                pgm.nodes.append(Command(self.token.val))

            self.token = self.lexer.read()

        return pgm

class Interpreter:
    def __init__(self, tree):
        self.tree = tree

    def visit(self, node):
        method_name = "visit_" + type(node).__name__
        visitor = getattr(self, method_name.lower())
        return visitor(node)

    def interpret(self):
        self.visit(self.tree)

    def visit_main(self, node):
        for each in node.nodes:
            self.visit(each)

    def visit_do(self, node):
        while counter:
            self.visit(node)

    def visit_if(self, node):
        if stack[-1]:
            self.visit(node.first)
        elif node.second:
            self.visit(node.second)

    def visit_literal(self, node):
        stack.append(node.val)

    def visit_command(self, node):
        run_cmd(node.val)

if source == "":
    with open("info.txt") as f:
        info = f.read()

    print(info)
else:
    main = Parser(Lexer(source)).parse()

    interpreter = Interpreter(main)
    interpreter.interpret()

    try:
        sys.exit(stack[-1])
    except IndexError:
        pass

```

---
Tags: code-challenge, restricted-source, language-design
---


title: Total Factorization

text:
# Question
Title: Total Factorization
# The challenge

Given positive integer input `n` (`n>1`), calculate the array of unique factorizations of `n`, not including `1`. Order does not matter.

## Test cases

```
2 => [[2]]
3 => [[3]]
4 => [[4],[2,2]]
5 => [[5]]
6 => [[6],[2,3]]
7 => [[7]]
8 => [[8],[2,2,2],[2,4]]
9 => [[9],[3,3]]
10 => [[10],[2,5]]
11 => [[11]]
12 => [[12],[3,4],[3,2,2],[2,6]]

```

## Scoring

This is code-golf, so lowest byte count wins!

# Answer
> 1 votes
# Jelly, 10 bytes

```
ÆfŒṖP€€Ṣ€Q

```

Try it online!

```
ÆfŒṖP€€Ṣ€Q
Æf          - prime factorization
  ŒṖ        - all partitions
    P€€     - Product of each sub-partition
       Ṣ€   - Sort each
         Q  - Remove duplicates

```

# Answer
> 2 votes
# Pyth, 9 14 bytes

```
{mS*Mds./M.pP

```

Try it online!

### How it works

```
{mS*Mds./M.pP
            P    Prime factorization of [the input]
          .p     All permutations of the prime factorization
       ./M       All partitions of each permutation
      s          Flattened by one level
 m               For each partition:
   *Md               Take the product of each piece
  S                  Sort the products
{                De-duplicate.

```

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