# Question
Title: Calculate the Gamma function for half-integer arguments
Gamma function is defined as

It is a well-known fact that for positive integers it coincides with a properly shifted factorial function: `Γ(n) = (n - 1)!`. However, a less famous fact is

> Γ(1/2) = π1/2

Actually, the Gamma function can be evaluated for all half-integer arguments, and the result is a rational number multiplied by π1/2. The formulas, as mentioned in Wikipedia, are:

(for n \> 0)

In this challenge, you should write code (program or function) that receives an integer `n` and returns the rational representation of **Γ(1/2 + n) / π1/2**, as a rational-number object, a pair of integers or a visual plain-text representation like `15/8`.

The numerator and denominator don't need to be relatively prime. The code should support values of `n` at least in the range -10 ... 10 (I chose 10 because 20! \< 264 and 19!! \< 232).

Test cases (taken from Wikipedia):

```
Input | Output (visual) | Output (pair of numbers)
0     | 1               | 1, 1
1     | 1/2             | 1, 2
-1    | -2              | -2, 1
-2    | 4/3             | 4, 3
-3    | -8/15           | -8, 15

```

# Answer
> 7 votes
# , 7 bytes

```
,0_.!÷/

```

Try it online! or verify all test cases.

### Trivia

Meet M!

M is a fork of Jelly, aimed at mathematical challenges. The core difference between Jelly and M is that M uses infinite precision for all internal calculations, representing results symbolically. Once M is more mature, Jelly will gradually become more multi-purpose and less math-oriented.

M is very much work in progress (full of bugs, and not really *that* different from Jelly right now), but it works like a charm for this challenge and I just couldn't resist.

### How it works

```
,0_.!÷/  Main link. Argument: n

,0       Pair with 0. Yields [n, 0].
  _.     Subtract 1/2. Yields [n - 1/2, -1/2].
    !    Apply the Π function. Yields [Π(n - 1/2), Π(-1/2)] = [Γ(n + 1/2), Γ(1/2)].
     ÷/  Reduce by division. Yields Γ(n + 1/2) ÷ Γ(1/2) = Γ(n + 1/2) ÷ √π.

```

# Answer
> 5 votes
# Octave, 27 bytes

```
@(n)rats(gamma(n+.5)/pi^.5)

```

Built-ins all the way.

Test suite on ideone.

# Answer
> 3 votes
# Pyth - ~~27~~ ~~26~~ ~~25~~ 24 bytes

Too cumbersome for my liking. Also, implicit input seems not to work with `W`. Uses the ~~second to last~~ first form listed above.

```
_W<QZ,.!yK.aQ*^*4._QK.!K

```

Test Suite.

# Answer
> 2 votes
# J, ~~20~~ ~~17~~ ~~19~~ 18 bytes

Saved 3 bytes using @Dennis's technique in his M, and another! This is a tacit verb.

```
x:@%&!/@(0.5-~,&0)

```

(Previous answers: `x:@%/@(!@-&0.5@,&0)`, `x:%/(!@-&0.5@,&0)`, `x:((%:o.1)%~!@-&0.5)`)

(Note that instead of being `-a/b`, it's `_arb`.)

Test cases:

```
   gamma =: x:@%&!/@(0.5-~,&0)
   gmR0  =: gamma"0    NB. apply to 0-cells of a list
   gamma 0
1
   gamma 1
1r2
   gamma 2
3r4
   gamma -1
_2
   gamma -2
4r3
   i:2
_2 _1 0 1 2
   gmR0 i:2
4r3 _2 1 1r2 3r4
   gmR0 i:5
_32r945 16r105 _8r15 4r3 _2 1 1r2 3r4 15r8 105r16 945r32

```

# Answer
> 2 votes
# Mathematica, ~~17~~ 15 bytes

```
(#-1/2)!/√π&

```

Uses factorial function since `gamma(n + 1/2) = (n - 1/2)!`.

There are only 12 characters now but it needs 15 bytes to be represented. The bytes are counted using UTF-8. `Sqrt = √` is 3 bytes from 5 bytes with `@` (2 bytes saved, thanks to @CatsAreFluffy) and `Pi = π` is 2 bytes (equal).

# Answer
> 1 votes
# Haskell, ~~81~~ ~~71~~ 69 bytes

```
import Data.Ratio
p=product
f n|n<0=1/(p[n+1%2..0-1])|0<1=p[1%2..n-1]

```

This seems bloated, but I'm not sure where to golf this from here. Any golfing suggestions are welcome.

**Edit:** Used the fact that the default step of range `[x..y]` is 1, and moved `product` to `p=product` to save two bytes.

**Ungolfing:**

```
import Data.Ratio
gamma_half n | n < 0     = 1 / ( product [ n + 1%2 .. (-1) ] )
             | otherwise = product [ 1%2 .. n-1 ]

```

# Answer
> 0 votes
# Ruby, ~~80~~ ~~59~~ 58 bytes

```
f=->n{n<0?(-1)**n/f[-n]:(1..n).reduce(1){|z,a|z*(a-1r/2)}}

```

Any golfing suggestions are welcome.

**Ungolfing:**

```
def half_gamma(n)
  if n < 0
    return (-1) ** n / f(-n)
  else
    # Is there an golfier way to write product([1/2,3/2..(2*n-1)/2])?
    return (1..n).reduce(1) {|z, a| z * (a - 1r/2)}
  end
end

```

---
Tags: code-golf, math, rational-numbers
---


title: Double run-length encoding

text:
# Question
Title: Double run-length encoding
Everyone knows what run-length encoding is. It has been the subject of many code-golf challenges already. We'll be looking at a certain variation.

### Example

```
Normal: 11222222222222222222233333111111111112333322
Run-length: 112(19)3(5)1(11)2333322

```

The number in parentheses specifies the number of times the previous symbol occurred. In the example, only runs of 5 or more characters were encoded. This is because encoding runs of 4 or less doesn't improve the character count.

## Challenge

Write a function/program that implements this variation of run-length encoding, but can also encode runs of two symbols. The runs of two symbols must also be enclosed in parentheses. A group will also be enclosed in parentheses. Your program must accept a string as input, and output the modified string with modifications that shorten the string.

### Example

```
Normal: 111244411144411144411167676767222222277777222222277777123123123123
Double run-length: 1112((444111)(3))67676767((2(7)7(5))(2))123123123123

```

### Notes

* `111` was not encoded because encoding it (`1(3)`) is not shorter.
* The string `444111` occurs 3 times so it is encoded.
* `676767` was not encoded because `((67)(4))` is longer than before.
* `222222277777222222277777` was not encoded as `((222222277777)(2))`. Why? Because `222222277777` itself can be reduced to `2(7)7(5)`.
* `123123123123` isn't encoded because your program is supposed to handle runs of two symbols, not three.

This is so shortest code wins. Tie-breaker is early submission.

---

If I missed anything, or if you are unsure of anything please notify me in the comments.

# Answer
# Retina, 162 bytes

```
+{`((\d)\2*(?!\2)(\d)\3*|\d)(?<1>\1)+
<<$1><$#1>>
<<([^<>]{1,7})><2>>
$1$1
<<([^<>]{1,3})><3>>
$1$1$1
<<([^<>]{1,2})><4>>
$1$1$1$1
}`<<(.)><(\d+)>>
$1($2)
T`<>`()

```

Try it online!
> 2 votes

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


# Question
Title: Briefest code to find vowels and print consonants
**Challenge: Read a string from user, print number of each vowel, then place all remaining chars in a line. Shortest answer wins!**

Output must look like this:

> Enter String: *Input*
>
> Vowel Count: a: *#*, e: *#*, i: *#*, o: *#*, u: *#*
>
> Remaining characters: *Vowel-less Input*

For example:

```
Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!

```

# Answer
> 5 votes
# 05AB1E, 62 bytes

### Code:

```
”‡Á•Ë: ÿ”,”Vowelš‹: ”?"aeiou"©vy": "¹y¢««}", "ý,“«¶šÞ: “ª¹®-J,

```

### Explanation:

There is a lot of string compression going on here. Here is a list of all strings that are compressed:

To see how the actual string compression works, see the Hello, World! answer, or an even more elaborate explanation at the bottom of the Code Review question. Without the string compression, the code looks like this:

```
"Enter String: ÿ","Vowel Count: "?"aeiou"©vy": "¹y¢««}", "ý,"Remaining characters: "¹®-J,

```

Or a more readable 3-part version:

```
"Enter String: ÿ",
"Vowel Count: "?"aeiou"©vy": "¹y¢««}", "ý,
"Remaining characters: "¹®-J,

```

**Part 1:**

We first push the string `"Enter String: ÿ"`. The `ÿ` here is used for *string interpolation*. But since the stack is empty, implicit input is requested. The `ÿ` will be substituted with the user input. We print this with a newline using `,`.

**Part 2:**

We first print the `"Vowel Count: "` string *without* a newline using `?`. After that, we push the `aeiou` string, `©`opy that to the register and map over the string using `v` and do the following:

```
vy": "¹y¢««}    # Mapping loop

v          }    # The loop itself
 y              # Push the current letter (which is a, e, i, o or u)
  ": "          # Push this string
      ¹         # Push the first input again
       y        # Push the letter again
        ¢       # Count the number of occurences of that letter in the input
         ««     # Concatenate to one single string, (e.g. "a: 4")

```

This leaves 5 different string onto the stack, the stack looks like this now:

```
stack: ['a: 0', 'e: 1', 'i: 0', 'o: 2', 'u: 0']

```

We join each element in the stack with `", "` using `ý`. After this, we print it with a newline using `,`.

**Part 3:**

We first push the string `"Remaining characters: "`. We push the first input again using `¹`. We then push `"aeiou"` which we retrieve from the register using `®`. After this, we remove all letters in `aeiou` using `-` and `J`oin this with the `Remaining characters`-string. Finally, we output this with a newline using `,`.

Uses **CP-1252** encoding. Try it online!.

# Answer
> 3 votes
# JavaScript (ES6), 165

Fixed error in output, thx @Neil
3 bytes saved thx @Dom Hastings

```
a=prompt`Enter String:`.replace(/[aeiou]/g,v=>(V[v]=-~V[v],''),V=[]);alert("Vowel Count: "+[...'aeiou'].map(v=>v+': '+(V[v]|0)).join`, `+`
Remaining characters: `+a)
```

# Answer
> 3 votes
## Python, 168 bytes

```
s=input('Enter String:')
v='aeiou'
print('Vowel Count: '+', '.join([a+':'+str(s.count(a)) for a in v])+'\nRemaining characters: '+''.join([a for a in s if a not in v]))

```

https://repl.it/CMzO/1

# Answer
> 2 votes
# Perl 5, 127 bytes

```
$_=<>;print"Enter String: ${_}Vowel Count:";for$s(a,e,i,o,u){print" $s: ".~~s/$s//g,$s!~u&&","}print"
Remaining characters: $_"

```

Many thanks to Dom Hastings (in a comment hereon) for 14 bytes.

# Answer
> 2 votes
# PostgreSQL, 295, 263 bytes

```
SELECT v "Enter string:", string_agg(r,', 'ORDER BY n) "Vowel Count:",TRANSLATE(v,'aeyiou','') "Remaining characters:"
FROM (SELECT 'LoremIpsumDolorSitAmetConsecuteurAdipscingElit!'::text v)s
,LATERAL(SELECT LENGTH(v)l)a
,LATERAL(SELECT c||': '||l-LENGTH(REPLACE(v,c,''))r,n FROM (VALUES('a',1),('e',2),('i',3),('o',4),('u',5))t(c,n))b
GROUP BY v

```

`**`SqlFiddleDemo`**`

Output:

```
╔══════════════════════════════════════════════════╦═══════════════════════════════╦══════════════════════════════════╗
║                  Enter string:                   ║         Vowel Count:          ║      Remaining characters:       ║
╠══════════════════════════════════════════════════╬═══════════════════════════════╬══════════════════════════════════╣
║ LoremIpsumDolorSitAmetConsecuteurAdipscingElit!  ║ a: 0, e: 4, i: 4, o: 4, u: 3  ║ LrmIpsmDlrStAmtCnsctrAdpscngElt! ║
╚══════════════════════════════════════════════════╩═══════════════════════════════╩══════════════════════════════════╝

```

Input: `(SELECT '...'::text v)s`

How it works:

* `(SELECT 'LoremIpsumDolorSitAmetConsecuteurAdipscingElit!'::text v)s` input
* `,LATERAL(SELECT LENGTH(v)l)a` \- length of input
* `(VALUES('a',1),('e',2),('i',3),('o',4),('u',5))` \- vowels with oridinal
* `SELECT c||': '||l-LENGTH(REPLACE(v,c,''))r,n` \- calculate number of occurences
* `string_agg(r,', 'ORDER BY n) ... GROUP BY v` combine result
* `TRANSLATE(v,'aeyiou','')` string without vowels

**EDIT 3:**

Removed additional `LATERAL`, input moved to table.

```
SELECT v"Enter string:",string_agg(r,', 'ORDER BY n)"Vowel Count:",TRANSLATE(v,'aeyiou','')"Remaining characters:"
FROM s,LATERAL(SELECT c||': '||LENGTH(v)-LENGTH(REPLACE(v,c,''))r,n FROM(VALUES('a',1),('e',2),('i',3),('o',4),('u',5))t(c,n))b
GROUP BY v

```

`**`SqlFiddleDemo`**`

# Answer
> 2 votes
## Lua, 242 Bytes

For a moment, I thought that it will be longer than SQL... still a monster for such a simple task.

```
t={}x="aeiou"i=io.write
x:gsub(".",function(c)t[c]=0 end)i("Enter string: ")z=io.read()s="Remaining characters: "..z:gsub(".",function(c)if x:find(c)then
t[c]=t[c]+1return""end end)i("Vowel Count: ")x:gsub(".",function(c)i(c..": "..t[c]..(c=="u"and"\n"or", "))end)i(s)

```

The job is done by the part

```
z:gsub(".",function(c)if x:find(c)then t[c]=t[c]+1return""end end)

```

Everything else is mainly for the purpose of outputing in the right format.

### Ungolfed

```
t={}                             -- create an empty array
x="aeiou"                        -- list of vowels
i=io.write                       -- shorthand for outputing
x:gsub(".",function(c)t[c]=0 end)-- create a celle at 0 for each vowel
i("Enter string: ")              -- output some boilerplate
z=io.read()                      -- take the input
s="Remaining characters: "..     -- save in s the concatenation of this string
  z:gsub(".",function(c)         -- and the result of gsubing on each character of the input
  if x:find(c)                   -- if the current char is a vowel
  then
    t[c]=t[c]+1                  -- increment its counter
    return""                     -- suppress it from the input
  end
end)

i("Vowel Count: ")               -- output some more boilerplate
x:gsub(".",function(c)           -- iterate over the vowels
  i(c..": "..t[c]..              -- output "l: #" appended with
    (c=="u"
        and"\n"                  -- "\n" if the current char is "u"
      or", "))                   -- ", " otherwise
end)
i(s)                             -- output the content of s

```

# Answer
> 2 votes
**Python, ~~220~~ 201 bytes**

This is my first submission on codegolf so go easy. :P

```
def f(y):
  global x;c=x.count(y);x=x.replace(y,'');return c;
x=input('Enter string: ');print('Vowel Count: a: {}, e: {}, i: {}, o: {}, u: {}'.format(*map(f,"aeiou")));print('Remaining characters: '+x)

```

**Ungolfed:**

```
def f(y):
  global x
  c=x.count(y)
  x=x.replace(y,'')
  return c;
x=input('Enter string: ')
print('Vowel Count: a: {}, e: {}, i: {}, o: {}, u: {}'.format(*map(f,"aeiou")))
print('Remaining characters: '+x)

```

**Output:**

```
Enter string: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!

```

# Answer
> 2 votes
# JavaScript, ~~190~~ 186 bytes

```
(s,a=[..."aeiou"].map(v=>(s.match(v,"g")||[]).length))=>`Enter String: ${s}
Vowel Count: ${[..."aeiou"].map((v,i)=>v+": "+a[i]).join`, `}
Remaining characters: `+s.replace(/[aeiou]/g,"")

```

I just remembered that literal newlines are only 1 byte! Also remembered to golf something I missed before.

# Answer
> 2 votes
# Java, 272 bytes

```
class L{public static void main(String[]v){String p=v[0],o="Enter String: "+p+"\nVowel Count:",d=" ",e="aeiou";for(char c:e.toCharArray()){o+=d+c+": "+p.replaceAll("[^"+c+"]","").length();d=", ";}System.out.println("\nRemaining characters: "+p.replaceAll("["+e+"]",""));}}

```

### Ungolfed

```
class L {
    public static void main(String[] v) {
        String input = v[0], result = "Enter String: " + input + "\nVowel Count:", delimiter = " ", vowels = "aeiou";
        for (char c : vowels.toCharArray()) {
            result += delimiter + c + ": " + input.replaceAll("[^" + c + "]", "").length();
            delimiter = ", ";
        }
        System.out.println("\nRemaining characters: " + input.replaceAll("[" + vowels + "]", ""));
    }
}

```

### Notes

* Input via program arguments: Save as `L.java`, compile with `javac L.java`, run with `java L LoremIpsumDolorSitAmetConsecuteurAdipscingElit!`

### Output

```
Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!

```

# Answer
> 1 votes
## PowerShell v2+, ~~196~~ 149 bytes

```
$z=read-host "Enter string"
"Vowel Count: "+(([char[]]"aeiou"|%{$_+": "+($z.length-($z=$z-creplace$_).length)})-join', ')
"Remaining characters: "+$z

```

Takes input via `read-host` with a prompt, save into `$z`.

We then output a string literal `"Vowel Count: "` concatenated with the result of a loop/join through the vowels to construct the `a: #, e: #,...` string. This is done by taking the current string's `.length` minus the new string's `.length` after we perform a case-sensitive replacement with `-creplace` (i.e., how many did we remove). In addition, we re-save the result of the replace back into `$z` for the next loop.

We then also output the second string literal concatenated with whatever is still left in `$z`.

This keeps the current specification intact, in that capital vowels are distinguished from lowercase vowels, since `-creplace` is explicitly case sensitive.

### Examples

```
PS C:\Tools\Scripts\golfing> .\briefest-code-find-vowels.ps1
Enter string: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!

PS C:\Tools\Scripts\golfing> .\briefest-code-find-vowels.ps1
Enter string: ProgrammingPuzzlesAndCodeGolf
Vowel Count: a: 1, e: 2, i: 1, o: 3, u: 1
Remaining characters: PrgrmmngPzzlsAndCdGlf

```

# Answer
> 1 votes
# Retina, 133 bytes

```
(a()|e()|i()|o()|u()|.)+
Enter string: $&¶Vowel count: a: $#2, e: $#3, i:$#4, o:$#5, u:$#6¶Remaining characters: $&
(?<=s:.+)[aeiou]
<empty-line>

```

Try it online!

Who is more fit for this challenge than Retina?

# Answer
> 1 votes
# Groovy, 181 177 bytes

online

```
{i->r=[:].withDefault{0};o=i.toLowerCase().replaceAll(/[aeiou]/,{r[it]++;''})
"Enter String: $i\nVowel Count: ${r.collect{k,v->"$k: $v"}.join(' ')}\nRemaining characters: $o"}

```

# Answer
> 1 votes
# Tcl, 184 (counting majuscule vowels) / 180 (ignoring them)

```
puts -nonewline {Enter String: }
flush stdout
gets stdin s
set c {Vowel Count:}
foreach v {a e i o u} {append c " $v: [regsub -all (?i)$v $s {} s]"}
puts "$c\nRemaining Characters: $s"

```

**Explanation**

Most of the code is actually dealing with the strict I/O requirements. The remainder works by doing a regular expression substitution (deletion) on the input string `$s` for every vowel and appending the vowel `$v` and associated number of substitutions to the output string `$c`.

The above code works for mixed-case vowels. Remove the `(?i)` option from the regular expression on the penultimate line for strictly minuscule vowels.

# Answer
> 1 votes
# C# 317 bytes

```
string t=Console.ReadLine();Dictionary v = new Dictionary<char,int>{{'a',0},{'e',0},{'i',0},{'o',0},{'u',0}};string o="";foreach(char c in t){if(v.Keys.Contains(c)){v[c]++;}else{o+=c;}}Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);Console.WriteLine("Remaining Characters: "+o);

```

Any suggestions, trying to learn to golf with C#. 1KB is obviously way bigger than the other answers though.

Ungolfed:

```
string t=Console.ReadLine();
Dictionary v = new Dictionary<char,int>
{
    {'a',0},
    {'e',0},
    {'i',0},
    {'o',0},
    {'u',0}
};
string o="";
foreach(char c in t)
{
    if(v.Keys.Contains(c))
    {
        v[c]++;
    }
    else
    {
        o+=c;
    }
}
Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);
Console.WriteLine("Remaining Characters: "+o);

```

# Answer
> 1 votes
# Python 162 Bytes

```
v,s="aeiou",input()
print "String:"+s+"\n"+"Vowel Count"+" ".join([c+":"+str(s.count(c)) for c in v])+"\n"+"Remaining Characters:"+filter(lambda x:v.count(x)<1,s)

```

# Answer
> 0 votes
## Ruby, 202 bytes

```
print"Enter String: ";t=gets;c=->(x){t.chars.count(x)};a="aeiou".chars
s=a.zip(a.map(&c)).map{|e|"#{e[0]}: #{e[1]}"}.join(", ");r=t.gsub(/[aeiou]/,"")
puts"Vowel Count: #{s}\nRemaining characters: #{r}"

```

# Answer
> 0 votes
## C++, 449 bytes

### Golfed:

```
#include <iostream>
#include <string>
int main(){std::string x;std::cout<<"Enter String: ",std::cin>>x;int a=0,e=0,i=0,o=0,u=0;for(int c=0;c<x.length();c++){switch(x[c]){case 'a':a++;x.erase(c,1);break;case 'e':e++;x.erase(c,1);break;case 'i':i++;x.erase(c,1);break;case 'o':o++;x.erase(c,1);break;case 'u':u++;x.erase(c,1);break;}}std::cout<<"\n Vowel Count: a: "<<a<<", e: "<<e<<", i: "<<i<<", o: "<<o<<", u: "<<u<<"\n Remaining characters: "<<x;}

```

### Ungolfed:

```
#include <iostream>
#include <string>

int main(){
    std::string x;
    std::cout<<"Enter String: ", std::cin>>x;
    int a=0,e=0,i=0,o=0,u=0;
    for(int c = 0; c < x.length(); c++){
        switch(x[c]){
            case 'a':
                a++;
                x.erase(c,1);
                break;
            case 'e':
                e++;
                x.erase(c,1);
                break;
            case 'i':
                i++;
                x.erase(c,1);
                break;
            case 'o':
                o++;
                x.erase(c,1);
                break;
            case 'u':
                u++;
                x.erase(c,1);
                break;
        }
    }
    std::cout<<"\n Vowel Count: a: "<<a<<", e: "<<e<<", i: "<<i<<", o: "<<o<<", u: "<<u<<"\n Remaining characters: "<<x;
}

```

# Answer
> 0 votes
# C++17, 313 bytes

```
#include <cctype>
#include <iostream>
#include <string>
using namespace std;int main(){int n,h[6]={0};string s,v="aeiou",r;cout<<"Enter String: ";getline(cin,s);for(c:s){h[n=v.find(tolower(c))+1]++;if(!n)r+=c;}cout<<"Vowel Count:";n=1;for(c:v)cout<<" "<<c<<": "<<h[n++];cout<<"\nRemaining Characters: "<<r<<"\n";}

```

I suppose I could make this just a function to eliminate standard boilerplate from the byte count.

**Ungolfed**

```
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main()
{
  int n;
  int histogram[6] = {0};   // { (consonants), A, E, I, O, U }
  string source;
  string vowels = "aeiou";  // vowel order matches the histogram
  string consonants;

  cout << "Enter String: ";
  getline( cin, source );

  for (c : source)
  {
    // n ← consonants=0, A=1, E=2, ...
    n = vowels.find( tolower(c) ) + 1;
    histogram[n]++;
    if (!n)
      consonants += c;
  }

  cout<<"Vowel Count:";
  n = 1;
  for (vowel : vowels)
    cout << " " << vowel << ": " << histogram[n++];

  cout << "\nRemaining Characters: " << consonants << "\n";
}

```

**Explanation**

Computes a histogram using the `std::string` lookup functions.

Again, you can eliminate 27 bytes from the count if only minuscule vowels matter. (Remove the first #include and the call to `tolower()`.)

# Answer
> 0 votes
# Ruby, ~~134~~ ~~133~~ 131 bytes

Because the other Ruby answer didn't respond to my suggestions, I golfed it down further myself.

-2 bytes from @manatwork

```
$><<"Enter String: "
r=gets.tr v='aeiou',''
puts"Vowel Count: #{v.chars.map{|e|e+": #{$_.count e}"}*', '}
Remaining characters: "+r

```

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


title: The Back-and-Forth Sequence

text:
# Question
Title: The Back-and-Forth Sequence
Imagine a path made up of `<` and `>` and ending in a `@`, e.g.

```
><>@

```

A walker starts on the left-most cell. He will traverse the path as follows:

* If the walker is on a `@` cell, he's reached the goal and is done.
* If the walker is on a `>` cell, the entire path shifts one step to the right, *cyclically, taking the walker with it*.
* If the walker is on a `<` cell, the entire path shifts one step to the left, *cyclically, taking the walker with it*.
* Afterwards, the walker takes a single step. If he's at either end of the path, he moves away from the end. Otherwise he keeps moving in the direction he moved on the last step (ignoring the rotation), walking right initially.

Let's work through the above example. The walker's position is marked with `^`:

```
><>@   --rotate-->  @><>
^                    ^
step right (first step):
@><>   --rotate-->  ><>@
  ^                  ^
step right:
><>@   --rotate-->  @><>
  ^                    ^
step left (dead end):
@><>   --rotate-->  ><>@
  ^                  ^
step left:
><>@   --rotate-->  @><>
^                    ^
step left:
@><>   Goal reached!
^

```

The walker visited **6** cells in the process (including the starting cell as well as the `@`, and counting each cell as often as it's visited).

Here is a small example, where the walker is transported across the edges by a rotation:

```
>>@   --rotate-->  @>>
^                   ^
step right (first step):
@>>   --rotate-->  >@>
  ^                ^
step right (dead end):
>@>   Goal reached!
 ^

```

This time the walker visited **3** cells.

We can easily turn this into an integer sequence:

* You're given a positive integer **N**, e.g. `9`.
* You compute the the binary representation of this integer, e.g. `1001`.
* Then turn `1` into `>` and `0` into `<` and append a `@`: `><<>@`.
* We associate with **N** the number of cells visited by the walker in the number constructed this way.

The first few elements of the resulting sequence are:

```
2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6,
6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7

```

This may seem quite arbitrary, but the resulting sequence actually turns out to have a lot of structure:

For reference, you can find the first 2048 numbers of the sequence in this pastebin.

## The Challenge

You guessed it: you're to compute the above sequence. You can do that one of three ways:

* You can produce an infinite sequence (while memory permits), either by continuously outputting (separated by non-numeric characters) values or by using some form of infinite generator in languages that support them. If you print an infinite stream to STDOUT, you don't have to print the numbers one by one, but make sure that every number would be printed after a finite amount of time (and in order). If you use this option, you should not take any input.
* You can take an integer **N** as input and produce the **N**th term of the sequence.
* You can take an integer **N** as input and produce everything *up to* the **N**th term of the sequence, either as a list or string using an unambiguous separator.

Since I don't want to penalise languages which can't easily convert between bases, instead of the integer **N** you may instead take the binary representation of **N**, using `0`s and `1`s as usual (as a list or string), with the most-significant bit first.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard rules apply.

### Background

This actually computes the number of "ticks" a straight-forward interpreter of my esoteric programming language Labyrinth would need to interpret the "path" as source code. In that case, the "walker" is simply the instruction pointer (which has a position and a direction), the `@` command terminates the program and `<` and `>` are source-code modification commands.

# Answer
# Jelly, 10 bytes

```
ð+\ḤiḤoµL‘

```

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer.

Try it online! or generate the first 2048 numbers.

### Background

Enumerate the positions underneath the path from **0** to **L**, giving a total of **L + 1** positions. **L** coincides the number of binary digits of the number **N** that encodes the path. With this notation, the walker starts at position **0**, the goal at position **L**.

With each step the walker takes, he gets one step closer to the goal (in the direction he's currently walking). Also, with each shift-step, depending on whether he walks with or against the shifting direction, he either increments or decrements his position by **2** modulo **L + 1**, or he stays in the current position.

To change direction, he has to land on position **L - 1** (facing **L**) or position **1** (facing **0**), then get shifted in his direction. The next step he takes will bring him back to his previous position, facing the opposite direction.

* If **L** is even, **L - 1** is odd, so he cannot advance from his initial position to **L - 1** directly. The only way to reach it is to pass through **L**, getting carried to **0** and taking the next step to land on **1**, then advancing to the right. This requires advancing **2L** positions, which can be done in no less than **L** steps.

However, after taking **L** steps without changing direction, he will have reached the goal. Adding one for the starting cell, we get a total of **L + 1** visited cells in this case.
* If **L** is odd, **L - 1** is even, so he can reach that position by getting shifted **(L - 1) / 2** times to the right. If position **L - 1** is underneath a **1** at that time, he will get shifted to position **L**, turn around, and step on position **L - 1** (facing leftwards).

This may or may not happen before he reaches his goal, so there are two cases to analyze:

+ If there are less than **(L + 1) / 2** occurrences of **1** in the binary expansion of **N**, taking **L** steps will not suffice to turn direction. Since these **L** steps bring the walker to his goal, adding one for the starting cell, we get a total of **L + 1** visited cells in this case.
    + If there are at least **(L + 1) / 2** occurrences of **1** in the binary expansion of **N**, advancing to the **((L + 1) / 2)**th occurrence will require **I** steps, where **I** is the initial position of that occurrence of **1**.

    Thus, after taking **I** steps, the walker is in position **L - 1**, facing leftwards. To turn directions again, he would have to walk advance leftwards to position **1**. However, as in the even case, since **(L - 1) - 1** is odd, this will require going through **0** and taking no less tha **L** steps.

    Since the initial distance to the goal in the left direction is **1**, after taking **I** steps, the walker finds himself at distance of **I + 1** from the goal after changing directions. Since **I \< L**, we have that **I + 1 ≤ L**, so the next **I + 1** steps will bring him to the goal.

    This gives a total of **I + I + 1 = 2I + 1** taken steps. Adding one for the starting cell, we get a total of **2I + 1 + 1 = 2(I + 1)** visited cells in this case.

### How it works

```
ð+\ḤiḤoµL‘  Main link. Argument: x (list of binary digits of N)

       µ    Monadic chain. Argument: x
        L   Compute L, the length of x.
         ‘  Increment to yield L + 1.

ð           Dyadic chain. Left argument: x. Right argument: L + 1
 +\         Compute the cumulative sum of x.
            This replaces the k-th one (and all zeroes to its right) with k.
   Ḥ        Unhalve; multiply all partial sums by 2.
    i       Find the first index of L + 1.
            This either gives I + 1, the 1-based index of the ((L + 1) / 2)-th one
            or 0 if the list doesn't contain L + 1.
            The result will be 0 if x contains less than (L + 1) / 2 ones
            or if L + 1 is an odd integer.
     Ḥ      Unhalve; yield either 2(I + 1) or 0.
      o     Logical OR with L + 1; if the previous operation returned a falsy
            value (i.e., if it yielded 0), replace that value with L + 1.

```
> 6 votes

# Answer
## Matlab (score=230,n=inf)

```
function w(s,f),b=[];e=0;for i=s:f,a=dec2bin(i);c=find(a=='1');g=numel(a)+1;if numel(c)>=g/2;if mod(g,2)==1,fprintf('%d ',g);else,d=c(g/2);fprintf('%d ',2*d);end,else,fprintf('%d ',g);end,e=e+1;if(e==100),e=0;fprintf('\n');end;end

```
* The function takes s as starting index and f as ending (type `inf` if you want to keep on to infinite).
* The function can go forever without any remarkable time-lag between any two outputs type `h=1000000000000000000000000000000000000000000000000000;w(h,h+1)` to make sure.
* The algorithm follows a mathematical approach that i will explain later, and it does confirm Martin's referenced list, basing on this program:

```
stored=[2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 14, 8, 8, 8, 14, 8, 14, 12, 12, 8, 8, 8, 14, 8, 14, 12, 12, 8, 14, 12, 12, 10, 10, 10, 10, 8, 8, 8, 14, 8, 14, 12, 12, 8, 14, 12, 12, 10, 10, 10, 10, 8, 14, 12, 12, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13];
b=[];for i=1:numel(stored)
a=dec2bin(i);
c=find(a=='1');
if numel(c)>=(numel(a)+1)/2
if mod(numel(a)+1,2)==1
b=[b numel(a)+1];
else
d=c((numel(a)+1)/2);
b=[b 2*d];
end
else
b=[b numel(a)+1];
end
end
for i=1:numel(stored)
if (b(i))
if b(i)~=stored(i)
'error',
end
end
end

```
* Since the algorithm verifies 2048 first testcases, I will blindly assume it would for any test case, so my algorithm works regarding few properties i discovered in this process without the pain of shifting and moving pointer:

1- if the twice the number of 1's in binary translation doesnt exceed the length of the sequnce `L` so the output is`L+1`

2- if the sequence length is even and the previous condition isnt set so the output is same `L+1`

3- otherwise, the output is twice the `L/2`th index of 1.
> 9 votes

# Answer
# Python, 122 119 113 110 108 107 103 bytes

```
def l(b):
 p=e=w=len(b);d=i=1
 while e:p+=1-2*b[w-e];d*=2*(1!=d-p>~w)-1;p-=d;e=(e-d)%-~w;i+=1
 return i

```

Takes input as a list of binary digits. Helper function to test:

```
b = lambda n: [int(d) for d in bin(n)[2:]]

```

Credit to Lynn for saving 7 bytes.
> 8 votes

# Answer
# Python 2, 99 bytes

```
def l(b):l=len(b);return(l>=sum(b)*2or l%2<1)and-~l or[i+1for i,c in enumerate(b)if b[i]][l/2]*2

```

Python port of Agawa001's brilliant answer.

Readable version:

```
def l(b):
    if len(b) >= 2*sum(b) or len(b)%2 == 0:
        return len(b) + 1

    return 2*[i+1 for i, c in enumerate(b) if b[i]][len(b)//2]

```
> 3 votes

# Answer
# MATL, ~~31~~, 25 bytes

```
BXHnQtHsy2/<w2\+~?2/Hfw)E

```

This is just a MATL version of Agawa001's algorithm, except it takes an integer input N and returns the N-th term in the sequence. It was tricky keeping up with all the elements in the stack! I had to resort to using a clipboard to avoid going insane. You can Try it online!

Can be made into a loop printing the first N terms by adding `:"@` before the code, and `]D` after.

Thanks to Luis Mendo for saving 6 whole bytes!
> 3 votes

# Answer
# Julia 0.4, 4̷4̷ 42 bytes

```
x->(k=endof(x)+1;try k=2find(x)[k/2]end;k)

```

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer and my Jelly answer.

Try it online!

### How it works

`find(x)` returns the 1-based indices of all non-zero elements of **x**. We attempt to access the resulting array at index **k / 2** and, if successful, overwrite **k** with twice the selected index.

This will fail if and only if one of the following is true:

* **k / 2** is a non-integral float, so and *InexactError* is raised.
* The index array has less than **k / 2** elements, so a *BoundsError* is raised.

In either case, overwriting **k** will fail, so its original value will be returned.
> 2 votes

# Answer
# Python 2, 74 bytes

```
def f(x):k=len(x)+1;print next((i*2for i in range(k)if k==2*sum(x[:i])),k)

```

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer and my Jelly answer.

Test it on Ideone.

### How it works

`next` attempts to find the first integer **2i** for which `k==2*sum(x[:i])` returns true. Since `x[:i]` contains **i** elements, this gives the 1-based index of the **(k / 2)**th **1**.

`next` will fail if **k/2** is non-integral or if **x** contains less than **k / 2** ones. In this case, the default value **k** is returned.
> 1 votes

# Answer
## JavaScript (ES6), 65 bytes

```
s=>(l=s.length+1)%2|!(m=s.match(`(0*1){$l/2}}`))?l:m[0].length*2

```

Accepts a binary string. Uses the bounce check from the various other answers.
> 1 votes

# Answer
## \>\<\>, 63 bytes

```
2r11&>}:?v{1->:l2-%?vr{{$>1+$}$:2=$@&101.
 +&?!^&n;>{1+^ .0+bf<

```

From the moment I saw the example pattern in this challenge, I knew which language to use :)

Using **N** to get the **N**th term.

Input assumed to be in binary at the stack. Rather than moving the walker around, this solution relies mostly on moving the tape under the walker.

Try it online!
> 0 votes

---
Tags: code-golf, number, sequence, counting
---


title: Outline a PNG image

text:
# Question
Title: Outline a PNG image
# Intro (semi fictional)

I'm the solo developer of a game, I'm already struggling with character design as is. Hence I've thought of a smart solution, I'll just use images for regular monsters, outline them a bit and suddenly they are boss monsters! That will save me from thinking up new bosses yay.
However, I have approximately 100 monster designs already and I wouldn't like duplicating them all and manually drawing an outline to the images...

# Challenge

Given a file name (of a PNG file) as input, you should write a program/function which will draw an outline around every non-transparent pixel. The program/function should save the output file to a new file called `a.png`

# What does outlining mean

Outlining is the process of adding non-transparent pixels in the place of transparent pixels, around pixels which were non-transparent already. Any transparent pixel has an opacity of exactly 0%, anything else is defined as non-transparent. Any pixel which will be outlined will have an opacity of 100%, aka the alpha channel of that pixel will be 255.

# Input

Your program/function should take 3 variables as input. Feel free to provide these as function parameters, read them from stdin or any other method which suits you best.

The first variable is the **file name**, which is always a PNG file.
The second variable is the **outline colour**, which is a round integer, you can also take the colour from 3 separate `r,g,b` byte values.
The third variable is the **outline width**, also an integer.

# Outline width

The width of the outline equals the maximum distance any transparent pixel should have to a non-transparent pixel in order to be outlined. The distance is calculated using the Manhattan distance between two points.
If the input image has only 1 non-transparent pixel, at `[0,0]` and the outline width is 2, then the following pixels will be coloured: `[0,1] [0,-1] [1,0] [-1,0] [1,1] [-1,-1] [1,-1] [-1,1] [2,0] [-2,0] [0,2] [0,-2]`, for these have a manhattan distance of 2 or less from the coloured pixel

# Test cases

The following test cases are scaled up 7 times for visibility, so every block of 7 pixels should be treated as a single pixel

These are the input images used for the test cases:

```
input1.png

```

```
input2.png

```

```
input3.png

```

These are the actual test cases:

```
input1.png, 0xFF0000, 0

```

```
input1.png, 0xFF0000, 1

```

```
input1.png, 0xFF0000, 2

```

```
input1.png, 0xFF0000, 3

```

```
input1.png, 0xFF0000, 10

```

```
input2.png, 0xFF0000, 2

```

```
input3.png, 0x000000, 2

```

Click here for the full Imgur album.

This is , standard loopholes apply! Feel free to submit your own images as test cases, since these pixel images aren't very creative ;)

# Answer
# Matlab, 202 bytes

```
function f(i,r,g,b,n);[i,~,a]=imread(i);[x,y]=ndgrid(abs(-n:n));d=permute([r,g,b,255]',3:-1:1);I=cat(3,i,a);J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I;imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4))

```

As always:

> Convolution is the key to success.

The function can be called like so:

```
f('my_image.png', red_int, green_int, blue_int, dist)

```

Commented:

```
function f(i,r,g,b,n)
[i,~,a]=imread(i);                   %read image and alpha channel
[x,y]=ndgrid(abs(-n:n));             %computations for convolution kernel
d=permute([r,g,b,255]',3:-1:1);      %create 'pixel' that will be inserted
I=cat(3,i,a);                        %concatenate image and alpha channel
J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I; %find border via convolution of kernel, insert pixels and recombine with original
imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4)) %write file

```
> 4 votes

# Answer
# PHP, 559 chars

## Ungolfed

```
<?php
error_reporting(0);
$p=$argv[1];
$img = ImageCreateFromPng($p);
$width = imagesx($img);
$height = imagesy($img);
$new = ImageCreateFromPng($p);
alphaFix($img);
alphaFix($new);
$inv = '2130706432';
for($w=0;$w<$width;$w++)
    for($h=0;$h<$height;$h++)
    {
        $color = ImageColorAt($img, $w, $h);
        if($color != $inv)
            for($x=0;$x<$width;$x++)
                for($y=0;$y<$height;$y++)
                {
                    if(abs($h - $y) + abs($w - $x) <= intval($argv[3]))
                    {
                        $_color = ImageColorAt($img, $x, $y);
                        if($_color == $inv)
                            imagesetpixel($new, $x, $y, hexdec($argv[2]));
                    }
                }
    }
imagepng($new, str_replace(".png", ".border.png", $p));

function alphaFix(&$img)
{
    $background = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $background);
    imagealphablending($img, false);
    imagesavealpha($img, true);
}
?>

```

## Golfed

```
<?error_reporting(0);$j=$argv[1];$g=ImageCreateFromPng($j);$e=imagesx($g);$b=imagesy($g);$l=ImageCreateFromPng($j);a($g);a($l);$f='2130706432';for($m=0;$m<$e;$m++)for($l=0;$l<$b;$l++){$d=ImageColorAt($g,$m,$l);if($d!=$f)for($k=0;$k<$e;$k++)for($i=0;$i<$b;$i++){if(abs($l-$i)+abs($m-$k)<=intval($argv[3])){$c=ImageColorAt($g,$k,$i);if($c==$f)imagesetpixel($l,$k,$i,hexdec($argv[2]));}}}imagepng($l,str_replace(".png",".border.png",$j));function a(&$g){$a=imagecolorallocate($g,0,0,0);imagecolortransparent($g,$a);imagealphablending($g,0);imagesavealpha($g,1);}

```

## Syntax

```
php outline.php "image1.png" 0xFF0000 1
                     |           |    |
                     |           |    *- Border Size
                     |           *------ Color HEX
                     *------------------ Image Name

```

## Examples

I made an Imgur album, because I slightly changed the images and there you can also see the arguments I passed my script.
> 2 votes

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


title: ASCII piano keyboard

text:
# Question
Title: ASCII piano keyboard
Piano keys are 3 characters wide, and 7 characters tall. However, if *every* key was 3 charactes wide, there wouldn't be enough room for the black keys. That's why some of the white keys have parts of them cut out. There are 3 types of white keys.

Keys with the right half missing (R):

```
____
|  |
|  |
|  |
|  |
|   |
|   |
|___|

```

Keys with the left half missing (L):

```
 ____
 |  |
 |  |
 |  |
 |  |
|   |
|   |
|___|

```

And keys with the left and right halves missing (M):

```
 ___
 | |
 | |
 | |
 | |
|   |
|   |
|___|

```

On a real keyboard, the pattern of these goes like this:

```
RMLRMML, RMLRMML, RMLRMML...

```

and repeats for a total of 88 keys. Now you can't see it when the keys are shown individually, but when you shove them together, you can see the black keys.

```
_________________________________________________________
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|___|___|___|___|___|___|

```

# Your task

Given a positive integer *N*, print this ASCII-art of a piano with *N* white keys. You should be able to handle any *N* from 1 to 52 inclusive (since real 88-key pianos have 52 white keys). Here is test output from 1 to 8, and after that the pattern increases in a similar fashion.

```
1
____
|  |
|  |
|  |
|  |
|   |
|   |
|___|

2
________
|  | | |
|  | | |
|  | | |
|  | | |
|   |   |
|   |   |
|___|___|

3
_____________
|  | | | |  |
|  | | | |  |
|  | | | |  |
|  | | | |  |
|   |   |   |
|   |   |   |
|___|___|___|

4
________________
|  | | | |  |  |
|  | | | |  |  |
|  | | | |  |  |
|  | | | |  |  |
|   |   |   |   |
|   |   |   |   |
|___|___|___|___|

5
____________________
|  | | | |  |  | | |
|  | | | |  |  | | |
|  | | | |  |  | | |
|  | | | |  |  | | |
|   |   |   |   |   |
|   |   |   |   |   |
|___|___|___|___|___|

6
________________________
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|   |   |   |   |   |   |
|   |   |   |   |   |   |
|___|___|___|___|___|___|

7
_____________________________
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|

8
________________________________
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|

```

And last but not least, here is a full 52 key output:

```
_________________________________________________________________________________________________________________________________________________________________________________________________________________
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|

```

Standard loopholes are banned, and the shortest answer in bytes wins!

# Answer
> 4 votes
# Pyth, ~~68~~ ~~65~~ 63 bytes

```
*lJ:+\|s@Lj;*L" |"_j4536 7*4Q" $"k\_jb+*4]J*2]K+\|*Q"   |":Kd\_

```

Try it online!

Test suite.

In this version, I just substituted the assignments (J and K) inside to save 2 bytes. Therefore, read the version below.

## Previous 65-byte version with explanation

```
J:+\|s@Lj;*L" |"_j4536 7*4Q" $"kK+\|*Q"   |"*lJ\_jb+*4]J*2]K:Kd\_

```

Try it online!

```
J:+\|s@Lj;*L" |"_j4536 7*4Q" $"k    This part generates the most irregular line.

        j;*L" |"_j4536 7            Generate the whole line by black magic
      @L                *4Q         Get the first (4*input) characters of it, with wrapping.
  +\|                               Add "|" in front of it (we took away the first "|")
 :                         " $"k    Replace the ending space by nothing
J                                   Store the line to J.

K+\|*Q"   |"      This part generates the line just below the irregular line.
    *Q"   |"      Repeat "   |" input times
 +\|              Prepend "|"
K                 Store to K

*lJ\_     Now we can actually start printing

*  \_     Repeat "_" ...
 lJ                      [the length of J] times
          (and implicitly print it out)

jb+*4]J*2]K

   *4]J             Repeat J 4 times
       *2]K         Repeat K 2 times
  +                 Concatenate them together
jb                  Join with newlines
                    (and implicitly print it out)

:Kd\_

:K      Replace in K
  d                  " "
   \_                    by "_"
        (and implicitly print it out)

```

### Black magic

```
We find the irregular line from input=7, and cut out the first "|":
"  | | | |  |  | | | | | |  |"
 2  1 1 1 2  2  1 1 1 1 1 2

j;*L" |"_j4536 7    Black magic.

         j4536 7    4536 converted to base 7: [1,6,1,4,0]
        _           Reverse: [0,4,1,6,1]
  *L" |"            Repeat " |" <each element> times:
                    [""," | | | |"," |"," | | | | | |"," |"]
j;                  Join by whitespace:
                    "  | | | |  |  | | | | | |  |"

```

# Answer
> 11 votes
## JavaScript (ES6), ~~155~~ ~~149~~ 147 bytes

```
n=>[`_`[r=`repeat`](n*4+(9>>n%7&1)),s=[...Array(n*12/7|0)].map((_,i)=>1998>>i%12&1?` |`:`  |`).join``,s,s,s,s=`   |`[r](n),s,`___|`[r](n)].join`\n|`

```

Where `\n` represents the literal newline character. Leverages the fact that all the lines after the first start with a `|` character. Explanation:

```
f=
n=>[                        // Start by building up a list of rows
 `_`[r=`repeat`](n*4+       // 4 underscores per key
  (9>>n%7&1)),              // Third and seventh keys have one extra
 s=[...Array(n*12/7|0)]     // Calculate total of white and black keys
  .map((_,i)=>              // Process each key in turn
   1998>>i%12&1?` |`:`  |`  // Bitmap of narrow and wide keys
  ).join``,                 // Join the keys together
 s,s,s,                     // Repeated 4 times in total
 s=`   |`[r](n),            // Full width part of the white keys
 s,                         // Repeated twice in total
 `___|`[r](n)               // Base of the white keys
].join`\n|`                 // Join the rows together
```

```
<input type="number" oninput="o.textContent=f(this.value);"><pre id=o>
```

Edit: Saved 2 bytes by fixing my misreading of the spec on the height of the keys.

# Answer
> 1 votes
# Ruby, 119 bytes

```
->n{puts ?_*(1+n*4+(0<=>-n%7%4)),(0..6).map{|i|("01"+("%b"%[0xAADAAAD,13][i/4]*99)).tr('10',' |_|'[i/6*2,2])[0,1+n*4]}}

```

**Ungolfed in test program**

```
f=->n{
  puts ?_*(1+n*4+(0<=>-n%7%4)),           #Draw 1+n*4 _'s for top row (one less if -n%7%4>0, black note), then...
  (0..6).map{|i|                          #Cycle through remaining 7 rows
    ("01"+("%b"%[0xAADAAAD,13][i/4]*99)).   #Generate string version of binary number corresponding to pattern, repeat 99 times.
    tr('10',' |_|'[i/6*2,2]                 #Binary 1-> space or underscore. Binary 0 -> | (These choices ensured no leading 0)
    )[0,1+n*4]                              #truncate to the right amount of keys.
  }
}

10.times{|j|f[j]}

```

# Answer
> 1 votes
# \>\<\>, 188 182 bytes

```
&0"_"o011.
.\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$
.v~:7=?;ao"|"o1+:0$0$
.>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$
 ^
.>"| _"{:}7=?$~::oooo1+:&:&(3*2+1$
>^
^
0120112
  | | | |  |

```

The number of white keys to display should be present on the stack at program start.

**Edit**: I managed to shave off a few bytes through combining the output for lines 5/6 and 7. Previous version:

```
&0"_"o011.
.\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$
.v~ao"|"o1+:0$0$.
.>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$
 ^
.>"|   "oooo1+:&:&(3*2+1$
 ^
 "|___"oooo1+:&:&=?;
0120112
  | | | |  |

```

# Answer
> 1 votes
# Python ~~3~~ 2, ~~191~~ ~~185~~ ~~180~~ ~~182~~ ~~171~~ ~~145~~ ~~144~~ ~~133~~ 132 bytes

```
def k(n):print"\n|".join(["_"*(4*n+(9>>n%7&1))]+[''.join("   ||"[1998>>j%12&1::2]for j in range(n*12/7))]*4+["   |"*n]*2+["___|"*n])

```

This could use some golfing but I've fiddled with the code so much already that I may not see where the golfable spots are. Any golfing suggestions are welcome.

**Edit:** Misread the spec on the height of the keys. This bug has been fixed.

**Edit:** Borrowed Neil's 12 key idea from his Javascript answer, removed some parentheses, and switched to Python 2 to save 11 bytes.

**Edit:** Lots of changes to get the function down to one `for` loop.

**Edit:** Now a program instead of a function.

**Edit:** Now using `print"\n|".join()` as suggested by Neil to save 11 bytes. Turned the program back into a function to save a byte.

# Answer
> 1 votes
# PHP, 238 bytes

```
$n=$argv[1];$s=str_repeat;echo'_'.$s($a=$s('_',28),$m=($n-$r=$n%7)/7).substr($a,0,$k=4*$r-($r&&$r!=3))."\n",$g='|'.$s($b='  | | | |  |  | | | | | |  |',$m).substr($b,0,$k)."\n",$g,$g,$g,$h='|'.$s('   |',$n)."\n",$h,'|'.$s('___|',$n)."\n";

```

As usual, prepend the code with `<?php` , put it into a PHP file (let's name it `keyboard.php`) and run it using:

```
$ php -d error_reporting=0 keyboard.php 55

```

Two more bytes can be saved on PHP7 by squeezing the initialization of `$n` and `$s` into their first use:

```
echo'_'.($s=str_repeat)($a=$s('_',28),$m=($n-$r=($n=$argv[1])%7)/7).substr($a,0,$k=4*$r-($r&&$r!=3))."\n",$g='|'.$s($b='  | | | |  |  | | | | | |  |',$m).substr($b,0,$k)."\n",$g,$g,$g,$h='|'.$s('   |',$n)."\n",$h,'|'.$s('___|',$n)."\n";

```

The ungolfed code, a test suite and other goodies can be found on github.

# Answer
> 0 votes
# C# 1683 bytes

So....after seeing Neil's answer above this is pretty embarrassing, but I'll post it anyway 'cause it took me a while (bless). I used C# to create mine. Inside the "Fncs" class I created an array of the typical order of keys. Then, I created a function which can allow the user to get an appropriate index for this array based on a given integer. In order to edit individual lines, I created a "PianoKeyboard" class which contains a dictionary storing multiple strings representing the individual lines. Finally, I created the "DrawKey" function which appends the appropriate text to the individual lines and the "GetKeys" function which returns the overall string value.

```
namespace ASCIIPiano{public enum WhiteKeyType{Left,Middle,Right}public static class Fncs{public static WhiteKeyType[] Order{get{return new WhiteKeyType[]{WhiteKeyType.Left,WhiteKeyType.Middle,WhiteKeyType.Right,WhiteKeyType.Left,WhiteKeyType.Middle,WhiteKeyType.Middle,WhiteKeyType.Right};}}public static PianoKeyboard DrawKey(this PianoKeyboard keyboard, WhiteKeyType type){keyboard.Append(1,"_____");if (type == WhiteKeyType.Left){keyboard.Append( 2,"|  | ");keyboard.Append( 3,"|  | ");keyboard.Append( 4,"|  | ");keyboard.Append( 5, "|  | ");}else if (type == WhiteKeyType.Middle){keyboard.Append(2, " | | ");keyboard.Append(3," | | ");keyboard.Append( 4," | | ");keyboard.Append(5," | | ");}else{keyboard.Append( 2," |  |");keyboard.Append(3, " |  |");keyboard.Append(4," |  |");keyboard.Append(5, " |  |");}keyboard.Append(6,"|   |");keyboard.Append(7,"|   |");keyboard.Append(8,"|___|");return keyboard;}public static int GetWhiteKeyIndex(this int number){return number % 7;}public static string GetKeys(this int quantityofwhitekeys){PianoKeyboard keyboard = new PianoKeyboard();for (int i = 0; i < quantityofwhitekeys; i++){WhiteKeyType key=Fncs.Order[i.GetWhiteKeyIndex()];keyboard.DrawKey(key);}return keyboard.TOTALSTRING;}}public class PianoKeyboard{public PianoKeyboard(){}private Dictionary<int, string> lines = new Dictionary<int, string>();public void Append(int index,string value){if (index > 8 || index < 1){throw new Exception("URGH!");}else{if (lines.Keys.Contains(index)){lines[index] += value;}else{lines.Add(index, value);}}}public string TOTALSTRING{get{string returner = "";foreach (int key in lines.Keys){returner += lines[key] + "\n";}return returner;}}}}

```

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


title: Print 100 Circles

text:
# Question
Title: Print 100 Circles
Goal: Create the smallest possible code to open a separate window, in which there are 100 circles of random sizes and colors.

Rules: All circles must be visible to the unassisted, naked eye, so in other words more than 2 pixels across, the background must be black, at least 5 different colors must be recognizable, and at all circles must fit within the window.

# Answer
# Mathematica 106 bytes

The code is fairly straightforward. A palette is a floating window. The 100 circles are stored in an array. The first `r`yields coordinates; the second `r` yields a radius.

```
CreatePalette[{Graphics[Array[{RandomColor[],Disk[99~(r=RandomReal)~{2},r@5]}&,100],Background->Black]}]

```
> 1 votes

# Answer
## Java, 352 Bytes

Yeah, I know, an applet, but still...

```
import java.applet.*;import java.awt.*;import java.util.*;public class C extends Applet{public void paint(Graphics a){Random b=new Random();int x,y,diameter;setBackground(Color.black);for(int c=1;c<=100;c++){a.setColor(new Color(b.nextInt(0xFFFFFF)));d=b.nextInt(getWidth()/10);x1=b.nextInt(getWidth());y1=b.nextInt(getHeight());a.drawOval(x,y,d,d);}}}

```

Ungolfed Code:

```
import java.applet.*;
import java.awt.*;
import java.util.*;

public class C extends Applet {
    public void paint(Graphics a) {

        Random b = new Random();

        int x, y, d;

        setBackground(Color.black);

        for (int c = 1; c <= 100; c++) {
            a.setColor(new Color(b.nextInt(0xFFFFFF)));

            d = b.nextInt(getWidth() / 10);
            x = b.nextInt(getWidth());
            y = b.nextInt(getHeight());

            a.drawOval(x, y, d, d);
        }

    }
}

```
> 0 votes

# Answer
# Python 2 PIL - 199 bytes

Making some assumptions of the rules based on OP's answer. Not optimally golfed in the sense that the image could be 5 pixels across and the circles could be all the same place with grayscale colors, but goes with the spirit of the rules.

```
import Image,ImageDraw,random
h=999
i=Image.new('RGB',(h,h))
g=random.randint
exec"r,x,y=g(0,50),g(0,h),g(0,h);ImageDraw.Draw(i).ellipse((x-r,y-r,x+r,y+r),(g(0,255),g(0,255),g(0,255)));"*100
i.show()

```
> 0 votes

---
Tags: code-golf
---


title: Between the Lines

text:
# Question
Title: Between the Lines
While doodling around on square-ruled paper the other day, I came up with the above negative-space font for digits. In case you haven't spotted it yet, the spaces between the above shapes yield the golden ratio **1.618033988749**. In this challenge, your task is to take a number as input and render it exactly as the example above shows.

Here is how these are created: all lines will be on a regular grid, so that the individual digits are made up of a small number of grid cells. Here are the shapes of the 10 digits (we'll ignore the decimal point for this challenge):

Yes, the **7** differs from the golden ratio example at the top. I kinda messed that up. We'll be going with this one.

Notice that each digit is five cells tall, and three cells wide. To render a number, you can imagine placing all its digits next to each other, such that there is exactly one empty column between each pair of digits. For example, taking `319` as input, we'd write:

Notice that we add one leading and trailing empty column. Now we invert the cells:

The output should then be the boundaries of the resulting polygons:

Of course you may generate the result in any other way, as long as the rendered output looks the same.

## Input

* You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, as a string, or list of digits. (You can't take a number as that wouldn't allow you to support leading zeros.)
* You may assume that there will be no more than 16 digits in the input.

## Output

* Output may either be displayed on screen or written to a file in a common image format.
* You may use both raster and vector graphics.
* In either case, the aspect ratio of the cells of the underlying grid needs to be 1 (that is, the cells should be squares).
* In the case of raster graphics, each cell should cover at least 20 by 20 pixels.
* The lines must be no wider than 10% of the cell size. I'm willing to give one or two pixels leeway due to aliasing here.
* Lines and background can be any two clearly distinguishable colours, but the shapes created by the lines must not be filled (that is the insides should be the background colour as well).
* There must be no gaps within each closed loop.
* Of course, the entire result must be visible.

## Test Cases

Here are 10 inputs, which together cover all possible pairs of adjacent digits, as well as every possible leading and trailing digit:

```
07299361548
19887620534
21456837709
39284106657
49085527316
59178604432
69471338025
79581224630
89674235011
97518264003

```

And here are the expected results for those:

Make sure that your code also works when given a single digit (I don't want to include the expected results here, because they should be obvious, and the test case section is bloated enough as it is).

# Answer
# BBC BASIC, 182 ASCII characters (tokenised filesize 175 bytes)

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

```
I.n$
F.j=0TOLENn$*4p=ASCM."?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@",VALM.n$,j/4+1,1)*4+1+j MOD4)F.k=0TO4p*=2q=64A.p
V.537;q;0;2585;0;q;537;-q;0;2585;0;-q;25;0;64;
N.MOVEBY 64,-320N.

```

Scoring: When the above program is pasted into the editor and run, the editor will expand the abbreviated keywords into full keywords onscreen, though they are actually only 1 byte after tokenisation. (Example `I.`=`INPUT` storage space 1 byte.)

**Explanation**

I will just explain what the VDU line does: it draws a box by bit-flipping the current pixel colour on the screen. This means that (with a bit of care with the corners) it is possible simply to draw one cell next to each other, and the intervening edge will cancel out and disappear due to double drawing.

Close examination will reveal that the top right and bottom left corners of a cell are drawn but the top left and bottom right are missing ("rounded") in order to make this work.

After the cell is drawn, the graphics cursor is moved up 32 pixels ready for the next cell to be drawn.

The rest of the program is a fairly straightforward ASCII bitmap decompression. The dimensions of the cell are 64x64 units for golfing/compatability with the way the bitmap is decompressed. `q` controls the size of the cell that is plotted: 64x64 units for a cell that is present, 0x0 for a cell that is absent.

**Ungolfed code**

```
  m$="?@\@?[@_?DTP?TT@?pv@?PTD?@TD?||@?@T@?PT@" :REM bitmap for digits, including column of filled cells at left. BBC strings are 1-indexed
  INPUTn$                                       :REM user input
  FORj=0 TO LENn$*4                             :REM iterate 4 times per input digit, plus once more (plot column 0 of imaginary digit to finish)
    d=VAL MID$(n$,j/4+1,1)                      :REM extract digit from n$ (1-character string). VAL of empty string = 0, so 123->1,1,1,1,2,2,2,2,3,3,3,3,0
    p=ASC MID$(m$,d*4+1+j MOD4)                 :REM get column bitmap from m$ d*4 selects digit, j MOD4 selects correct column of digit, add 1 to convert to 1-index
    FORk=0TO4                                   :REM for each cell in the column
      p*=2                                      :REM bitshift p
      q=64ANDp                                  :REM find size of cell to draw. 64 for a filled cell, 0 for an absent cell.
      VDU537;q;0;                               :REM line q units right, inverting existing screen colour. Draw last pixel (will be inverted next line)
      VDU2585;0;q;                              :REM line q units up, inverting existing screen colour. Dont draw last pixel (will be filled in next line)
      VDU537;-q;0;                              :REM line q units left, inverting existing screen colour. Draw last pixel (will be inverted next line)
      VDU2585;0;-q;                             :REM line q units down, inverting existing screen colour. Dont draw last pixel (avoid inverting 1st pixel of 1st line)
      VDU25;0;64;                               :REM move up 64 units for cell above
    NEXT
    MOVEBY 64,-320                              :REM move right and down for next column.
  NEXT

```

**Output**

The `MOVE`s are just get the output to appropriate heights on the screen. BBC basic uses 2 units = 1 pixel in this mode, so the cells are actually 32x32 pixels.
> 1 votes

# Answer
# Octave, ~~233 225 216~~ 213 bytes

```
o=@ones;l=z=o(5,1);for k=input('')-47;l=[l,reshape(dec2bin([448,22558,8514,10560,3936,2376,328,15840,320,2368](k),15),5,[])-48,z];end;L=~o(size(l)+2);L(2:6,2:end-1)=l;O=o(3);O(5)=-8;M=~conv2(kron(L,o(25)),O);imshow(M)

```

Here the first test case (from a resized screen capture, s.t. it fits my monitor=):

```
o=@ones;
l=z=o(5,1);                   %spacer matrices
for k=input('')-47;           %go throu all input digis
                              %decode the matrices for each digit from decimal
l=[l,reshape(dec2bin([448,22558,8514,10560,3936,2376,328,15840,320,2368](k),15),5,[])-48,z];
end
L=~o(size(l)+2);           %pad the image
L(2:6,2:end-1)=l;
O=o(3);O(5)=-8;               %create edge detection filter
imshow(~conv2(kron(L,o(25)),O)) %image resizing /edge detection (change 25 to any cell size you like)

```

The input can be arbitrary length, like e.g. `'07299361548'`

> Convolution is the key to success.
> 10 votes

# Answer
# Html+JavaScript ES6, 352

Test running the snippet below

```
<canvas id=C></canvas><script>s=prompt(),C.width=-~s.length*80,c=C.getContext("2d"),[...s].map(d=>[30,d*=3,++d,++d].map(w=a=>{for(a=parseInt("vhvivgtlnllv74vnltvlt11vvlvnlv0"[a],36)*2+1,p=1,y=100,i=64;i>>=1;p=b,y-=20)c.moveTo(x+20,y),b=a&i?1:0,c[b-p?'lineTo':'moveTo'](x,y),(a^q)&i&&c.lineTo(x,y-20);q=a,x+=20}),q=63,x=0),w(30),w(0),c.stroke()</script>
```

*Less golfed*

```
s=prompt(),C.width=-~s.length*80,c=C.getContext("2d"),
w=a=>{
  a=parseInt("vhvivgtlnllv74vnltvlt11vvlvnlv0"[i],36)*2+1
  for(p=1,y=100,i=32;i;p=b,y-=20,i>>=1)
    c.moveTo(x+20,y),
    b=a&i?1:0,
    c[b-p?'lineTo':'moveTo'](x,y),
    (a^q)&i&&c.lineTo(x,y-20)
  q=a
  x+=20
},
[...s].map(d=>[30,d*=3,++d,++d].map(w),q=63,x=0),
w(30),w(0)
c.stroke()

```
> 6 votes

# Answer
# Javascript ES6, 506 bytes

```
a=>{with(document)with(body.appendChild(createElement`canvas`))with(getContext`2d`){width=height=(a.length+2)*80;scale(20,20);translate(1,1);lineWidth=0.1;beginPath();["oint",...a.map(i=>"05|7agd7|oint 067128a45|oicgmnt 01de25|oil9amnt 01de23fg45|oint 03fh5|68ec6|oint 03fg45|oij78knt 05|9agf9|oij78knt 01dh5|oint 05|78ed7|9agf9|oint 03fg45|78ed7|oint".split` `[i]),"05"].map(i=>{i.split`|`.map(i=>[...i].map((e,i,_,p=parseInt(e,36),l=~~(p/6),r=p%6)=>i?lineTo(l,r):moveTo(l,r)));translate(4,0)});stroke()}}

```

Ungolfed:

```
a=>{                                            // anonymous function declaration, accepts array of numbers
  with(document)                                // bring document into scope
  with(body.appendChild(createElement`canvas`)) // create canvas, drop into html body, bring into scope
  with(getContext`2d`){                         // bring graphics context into scope
    width=height=(a.length+2)*80;               // set width and height
    scale(20,20);                               // scale everything to 20x
    translate(1,1);                             // add padding so outline doesn't touch edge of canvas
    lineWidth=0.1;                              // have to scale line width since we scaled 20x
    beginPath();                                // start drawing lines
    ["oint",                                    // beginning "glyph", draws left end of negative space, see below
     ...a.map(i=>`05|7agd7|oint                 // glyphs 0-9 encoded as vertices
                  067128a45|oicgmnt             //   glyphs seperated by " "
                  01de25|oil9amnt               //   lines within each glyph seperated by "|"
                  01de23fg45|oint               //   a single vertex is stored as a base36 char
                  03fh5|68ec6|oint              //     where a number corresponds to one of the verts shown below:
                  03fg45|oij78knt               //        0  6 12 18 24
                  05|9agf9|oij78knt             //        1  7 13 19 25
                  01dh5|oint                    //        2  8 14 20 26
                  05|78ed7|9agf9|oint           //        3  9 15 21 27
                  03fg45|78ed7|oint`            //        4 10 16 22 28
       .split` `[i]),                           //        5 11 17 23 29
     "05"]                                      // end "glyph", draws right end of negative space, see above
      .map(i=>{                                 // for each glyph string
        i.split`|`                              // seperate into list of line strings
          .map(i=>[...i]                        // convert each line string into list of chars
            .map((e,i,_,p=parseInt(e,36),       // convert base36 char to number
                  l=~~(p/6),r=p%6)=>            // compute x y coords of vertex
              i?lineTo(l,r):moveTo(l,r)));      // draw segment
        translate(4,0)});                       // translate origin 4 units to right
    stroke()}}                                  // draw all lines to canvas

```

Assumes there's a `<body>` to append the canvas to, tested in Firefox 46.

Example run (assigning anonymous function to f):

```
f([1,0,3])

```

yields:
> 5 votes

# Answer
# Java, 768 bytes

```
import java.awt.*;import java.awt.image.*;class G{public static void main(String[]v)throws Exception{int s=20,n=v[0].length(),i=0,j,w=(n*3+n+1)*s,h=5*s,a[][]={{6,7,8},{0,2,3,10,11,12,13},{1,6,8,13},{1,3,6,8},{3,4,5,6,8,9},{3,6,8,11},{6,8,11},{1,2,3,4,6,7,8,9},{6,8},{3,6,8}};BufferedImage o,b=new BufferedImage(w,h,1);Graphics g=b.getGraphics();g.setColor(Color.WHITE);for(;i<n;i++)for(j=0;j<15;j++){int c=j;if(java.util.Arrays.stream(a[v[0].charAt(i)-48]).noneMatch(e->e==c))g.fillRect((1+i*4+j/5)*s,j%5*s,s,s);}o=new BufferedImage(b.getColorModel(),b.copyData(null),0>1,null);for(i=1;i<h-1;i++)for(j=1;j<w-1;j++)if((b.getRGB(j+1,i)|b.getRGB(j-1,i)|b.getRGB(j,i+1)|b.getRGB(j,i-1))<-1)o.setRGB(j,i,-1);javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}}

```

### Ungolfed

```
import java.awt.*;
        import java.awt.image.BufferedImage;

class Q79261 {
    public static void main(String[] v) throws Exception {
        int scale = 20, n = v[0].length(), i = 0, j, width = (n * 3 + n + 1) * scale, height = 5 * scale, values[][] = {{6, 7, 8}, {0, 2, 3, 10, 11, 12, 13}, {1, 6, 8, 13}, {1, 3, 6, 8}, {3, 4, 5, 6, 8, 9}, {3, 6, 8, 11}, {6, 8, 11}, {1, 2, 3, 4, 6, 7, 8, 9}, {6, 8}, {3, 6, 8}};
        BufferedImage output, temp = new BufferedImage(width, height, 1);
        Graphics g = temp.getGraphics();
        g.setColor(Color.WHITE);
        for (; i < n; i++)
            for (j = 0; j < 15; j++) {
                int finalJ = j;
                if (java.util.Arrays.stream(values[v[0].charAt(i) - 48]).noneMatch(e -> e == finalJ))
                    g.fillRect((1 + i * 4 + j / 5) * scale, j % 5 * scale, scale, scale);
            }
        output = new BufferedImage(temp.getColorModel(), temp.copyData(null), 0 > 1, null);
        for (i = 1; i < height - 1; i++)
            for (j = 1; j < width - 1; j++)
                if ((temp.getRGB(j + 1, i) | temp.getRGB(j - 1, i) | temp.getRGB(j, i + 1) | temp.getRGB(j, i - 1)) < -1)
                    output.setRGB(j, i, -1);
        javax.imageio.ImageIO.write(output, "png", new java.io.File("a.png"));
    }
}

```

### Notes

* Input is a single string as argument. How to use: `javac G.java`, `java G 80085`
* I'm starting with a black canvas, then I'm adding the numbers as white positives. I create a copy of the image and then flip every black pixel that has 4 black neighbours on the original image.

### Outputs

Some single digits:
> 3 votes

# Answer
# Python 3, 326 325 bytes

```
import numpy
from skimage import io,transform as t,filters as f
r=[[1]*5,[0]*5]
for c in map(int,input()):r+=[map(float,bin(0x3f1fa7e1bd7b5aff84ff6b7fd6f087ff5ff6bf)[2:][15*c+5*i:15*c+5*-~i])for i in[0,1,2]]+[[0]*5]
r+=[[1]*5]
p=[[1]*len(r)]
r=p+list(zip(*r))+p
io.imsave("o.png",1-f.sobel((t.rescale(numpy.array(r),16,0))))

```
> 2 votes

# Answer
# R, too many bytes to golf (~~1530+~~ 1115)

```
library(reshape2);library(ggplot2);library(png)
M=matrix(1,5,3)
M=lapply(list(c(7:9),c(1,3,4,11:14),c(2,7,9,14),c(2,4,7,9),c(4:7,9,10),c(4,7,9,12),c(7,9,12),c(2:5,7:10),c(7,9),c(4,7,9)),function(x){M[x]=0;M})
g=function(P){
S=matrix(0,5,1)
R=NULL
for(N in P){R=Reduce(cbind2,list(R,S,M[[N+1]]))}
cbind(R,S)}
p=function(P){
o=t(apply(g(P),1,rev))
ggplot(melt(o),aes(x=Var1,y=Var2))+geom_raster(aes(fill=value))+coord_flip()+scale_fill_continuous(guide=FALSE,high="#FFFFFF",low="#000000")+scale_y_reverse()+scale_x_reverse()+theme_bw()+theme(panel.grid=element_blank(),panel.border=element_blank(),panel.background=element_blank(),axis.title=element_blank(),axis.text=element_blank(),axis.ticks=element_blank(),plot.margin=unit(c(0,0,0,0),"mm"))+ggsave("t.png",width=dim(o)[2]/2.5,height=2,units="in",dpi=99)
q=readPNG("t.png")
k=q[,,1]
b=replace(k,k==1,0)
for(i in 1:nrow(k)){
for(j in 1:ncol(k)){
u=(i==nrow(k))
v=(j==ncol(k))
if(u&v){b[i,j]=1;break}
if((i==1)|u|(j==1)|v){b[i,j]=1;next}else{if(all(k[c((i-1):(i+1)),c((j-1):(j+1))])){b[i,j]=1}else{b[i,j]=0}}}}
q[,,1:3]=abs(replace(k,b==1,0)-1)
writePNG(q,"t.png")}

# run p(c(0,1,2,3,4,5))

```

lol at writing to disk, then reading from disk edit away the black fill.
> 2 votes

# Answer
## C#, 768 773 776 bytes

```
namespace System.Drawing{class P{static void Main(string[]a){uint[]l={0xEBFBFFFC,0xB89B21B4,0xABFFF9FC,0xAA1269A4,0xFFF3F9FC};var w=a[0].Length*80+20;var b=new Bitmap(w,100);var g=Graphics.FromImage(b);g.FillRectangle(Brushes.Black,0,0,w,100);for(int i=0;i<a[0].Length;i++)for(int r=0;r<5;r++)for(int c=0;c<3;c++)if((l[r]&((uint)1<<(175-a[0][i]*3-c)))>0)g.FillRectangle(Brushes.White,20*(1+i*4+c),20*r,20,20);for(int x=1;x<w-1;x++)for(int y=1;y<99;y++)if(b.GetPixel(x,y).B+b.GetPixel(x+1,y).B+b.GetPixel(x,y+1).B+b.GetPixel(x,y-1).B+b.GetPixel(x+1,y-1).B+b.GetPixel(x+1,y+1).B+b.GetPixel(x-1,y+1).B+b.GetPixel(x-1,y-1).B==0)b.SetPixel(x,y,Color.Red);for(int x=1;x<w-1;x++)for(int y=1;y<99;y++)if(b.GetPixel(x,y).R>0)b.SetPixel(x,y,Color.White);b.Save(a[0]+".bmp");}}}

```

Takes the number as command line argument. Outputs a nice, clean, non-aliased BMP image with the number as the name.

Original before golfing:

```
namespace System.Drawing
{
    class P
    {
        static void Main(string[] args)
        {
            var numbers = args[0];
            uint[] lines = {
                0xEBFBFFFC, // 111 010 111 111 101 111 111 111 111 111 00
                0xB89B21B4, // 101 110 001 001 101 100 100 001 101 101 00
                0xABFFF9FC, // 101 010 111 111 111 111 111 001 111 111 00
                0xAA1269A4, // 101 010 100 001 001 001 101 001 101 001 00
                0xFFF3F9FC  // 111 111 111 111 001 111 111 001 111 111 00
            };
            var width = numbers.Length*4 + 1;
            var bmp = new Bitmap(width*20, 5*20);
            using (var gfx = Graphics.FromImage(bmp))
            {
                gfx.FillRectangle(Brushes.Black, 0, 0, width*20+2, 5*20+2);
                // Process all numbers
                for (int i = 0; i < numbers.Length; i++)
                {
                    var number = numbers[i]-'0';
                    for (int line = 0; line < 5; line++)
                    {
                        for (int col = 0; col < 3; col++)
                        {
                            if ((lines[line] & ((uint)1<<(31-number*3-col))) >0)
                                gfx.FillRectangle(Brushes.White, 20*(1 + i * 4 + col), 20*line, 20 , 20 );
                        }
                    }
                }
                // Edge detection
                for (int x = 1; x < width*20-1; x++)
                {
                    for (int y = 1; y < 5*20-1 ; y++)
                    {
                        if (bmp.GetPixel(x,y).B +
                            bmp.GetPixel(x + 1, y).B +
                                bmp.GetPixel(x, y + 1).B +
                                bmp.GetPixel(x, y - 1).B +
                                bmp.GetPixel(x + 1, y - 1).B +
                                bmp.GetPixel(x + 1, y + 1).B +
                                bmp.GetPixel(x - 1, y + 1).B +
                                bmp.GetPixel(x - 1, y - 1).B == 0)
                                bmp.SetPixel(x, y, Color.Red);
                    }
                }
                // Convert red to white
                for (int x = 1; x < width * 20 - 1; x++)
                {
                    for (int y = 1; y < 5 * 20 - 1; y++)
                    {
                        if (bmp.GetPixel(x, y).R>0)
                            bmp.SetPixel(x, y, Color.White);
                    }
                }
            }
            bmp.Save(@"c:\tmp\test.bmp");
        }
    }
}

```
> 1 votes

# Answer
# Mathematica 328 bytes

```
j@d_:=Partition[IntegerDigits[FromDigits[d/.Thread[ToString/@Range[0,9]->StringPartition["75557262277174771717557117471774757711117575775717",5]],16],2, 20]/.{0->1,1->0},4];j@"*"=Array[{1}&,5];
w@s_:=  ColorNegate@EdgeDetect@Rasterize@ArrayPlot[Thread[Join@@Transpose/@j/@Characters@(s<>"*")],Frame->False,ImageSize->Large]

```

---

```
w["07299361548"]
w["19887620534"]

```

---

## Explanation

Four bits will be used in each of 5 lines of cells for each input digit.

`"75557262277174771717557117471774757711117575775717"`represents 0 to 9 as bitmaps.

The first 5 digits in the large integer above, namely `75557` indicate how each array row for zero should be displayed. `7` will represent `{0,1,1,1}`, that is, a white cell, followed, on its right, by 3 black cells; the leading `0` is a blank space to separate displayed digits. `5` corresponds to `{0,1,0,1}`, that is white, black, white, black cells.

The following produces a list of replacement rules:

```
Thread[ToString /@ Range[0, 9] -> StringPartition["75557262277174771717557117471774757711117575775717", 5]]

```

> {"0" -\> "75557", "1" -\> "26227", "2" -\> "71747", "3" -\> "71717", "4" -\> "55711", "5" -\> "74717", "6" -\> "74757", "7" -\> "71111", "8" -\> "75757", "9" -\> "75717"}

Note that when `3` is input, it will be replaced by `71717` This representation is expressed in binary:

```
p = Partition[IntegerDigits[FromDigits["3" /. {"3" -> "71717"}, 16], 2, 20], 4]

```

> {{0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}}

Its black-white inverse is found by simply exchanging the `1`s and `0`s.

```
q = p /. {0 -> 1, 1 -> 0}

```

> {{1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}}

---

Let's see what `p` and `q` look like when displayed by `ArrayPlot`:

```
ArrayPlot[#, Mesh -> True, ImageSize -> Small, PlotLegends -> Automatic] & /@ {p, q}

```

---

This simply joins the arrays of zeros and ones for each digit before rendering the big array via `ArrayPlot`. `*` is defined in `j` as the final vertical space after the last digit.

```
Thread[Join @@ Transpose /@ j /@ Characters@(s <> "*")]

```
> 1 votes

---
Tags: code-golf, number, graphical-output, typography
---


title: Draw a phi triangle

text:
# Question
Title: Draw a phi triangle
*Clarification: Basically, you need to make this*

Euler's totient function has the name phi.

Let's try to calculate phi(8)

First, list all numbers 8 and under backwards, not including 0 or under

```
8
7
6
5
4
3
2
1

```

Now find which numbers don't share a factor with 8 (1 doesn't count), and place a `#` in their place.

```
8
#
6
#
4
#
2
#

```

Remove the numbers.

```
#

#

#

#
                                                 -

```

Now do this, but string the outputs together in a triangle

```
        9
       88
      777
     6666
    55555
   444444
  3333333
 22222222
111111111
---------
123456789

```

`#` out non-factor sharing numbers

```
        9
       8#
      7##
     6#66
    5####
   4#4#4#
  3##3##3
 2#2#2#2#
#########

```

Remove numbers:

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

```

This would be the output for input 9 (since 9 columns.)

Leading + trailing newlines allowed.

# Answer
# MATL, ~~17~~ 15 bytes

```
:Gq:!Zd1=RP35*c

```

**Try it online!**

If a leading newline is acceptable: **13 bytes**:

```
:t!Zd1=RP35*c

```

### Explanation

```
:     % Take input N. Generate row vector [1 2 ... N]
Gq:   % Row vector [1 2 ... N-1].
      % (In the 13-byte version this is replaced by function `t`, which duplicates
      % the array [1 2 ... N])
!     % Transpose into column vector
Zd    % GCD, element-wise with broadcast. Gives (N-1)×N matrix
1=    % True for entries that equal 1, corresponding to relatively prime pairs.
      % The rest of entries are set to false, i.e. 0.
R     % Upper triangular part: set values below diagonal to 0
P     % Flip matrix vertically
35*   % Multiply each entry by 35 (ASCII for '#')
c     % Convert to char. 0 will be displayed as a space. Implicitly display

```
> 7 votes

# Answer
# Jelly, ~~20~~ 18 bytes

```
RR⁶”#g’¥?€"Rz⁶U'j⁷

```

Try it online!
> 3 votes

# Answer
# Pyth - 22 bytes

Will try to golf further.

```
j_.tmsm@"# "n1idkSdSQd

```

Try it online here.
> 3 votes

# Answer
## JavaScript (ES6), 112 bytes

```
n=>[...s=` `.repeat(n)].map(_=>s.replace(/./g,_=>`# `[+g(n+1,i++)],n-=i=1),g=(i,j)=>i?i>j||g(j%i,i):j>1).join`\n`

```

Where `\n` represents the literal newline character. Alternative solution, also 112 bytes:

```
n=>(s=`# `.repeat(n)).replace(r=/../g,_=>s.replace(r,m=>m[+g(n+1,i++)],n-=i=1)+`
`,g=(i,j)=>i?i>j||g(j%i,i):j>1)

```
> 2 votes

# Answer
# Java, ~~162~~ 158 bytes

```
int g(int a,int b){return a<1?b:g(b%a,a);}
String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;)r+=i+j<n|g(n-i,j++)>1?" ":"#";r+="\n";}return r;}

```

Full program (not updated)

```
import java.util.Scanner;

public class Q79082 {
    int gcd_ungolfed(int a,int b){
        if(a==0) return b;
        return gcd_ungolfed(b%a,a);
    }
    void draw_ungolfed(int n){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(i+j<=n || gcd_ungolfed(n+1-i,j)!=1){
                    System.out.print(" ");
                }else{
                    System.out.print("#");
                }
            }
            System.out.println();
        }
    }
    int g(int a,int b){return a<1?b:g(b%a,a);}
    String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;j++)r+=(i+j<n||g(n-i,j)>1)?" ":"#";r+="\n";}return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        new Q79082().draw_ungolfed(n);
        System.out.println(new Q79082().d(n));
    }
}

```

Input/output:

```
9

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

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

```
> 1 votes

# Answer
# SQL (PostGreSQL9.4), 239 ~~291~~ bytes

Creates a prepared statement that can be executed. I'm sure I can probably take quite a few bytes out of this, but I'll have to pick away at it later. Does a cross join on a range of 1 to n. Calculates the GCD in a lateral join. Where the GCD is 1 and the series A is greater than series B output a '#' otherwise a space. Aggregate the results up into a string grouped by series B.

```
prepare p(int)as
select string_agg(coalesce(CASE WHEN b<=a AND x=1THEN'#'END,' '),'')from generate_series(1,$1)a,generate_series(1,$1)b,LATERAL(SELECT MAX(G)x FROM generate_series(1,LEAST(a,b))g WHERE a%g+b%g=0)g
group by b
order by b desc

```

Run in the following way

```
execute p(13)

string_agg
----------------

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

```

And cleaned up with

```
deallocate p

```
> 1 votes

# Answer
# Ruby, 84 bytes

```
->n{s=[];n.times{|i|j=0;m=n-i;s<<(?#*n).gsub(/./){m.gcd(j+=1)>1||m>j ?' ':$&}};s*$/}

```
> 0 votes

# Answer
## Python 2 (120 bytes)

```
g=lambda m,n:m if n<1 else g(n,m%n)
r=range(input())
for i in r[:0:-1]:print''.join('# '[i>j+1 or g(i,j+1)>1]for j in r)

```
> 0 votes

---
Tags: code-golf, ascii-art, number-theory, division
---