18
\$\begingroup\$

These are ASCII dandelions:

   \|/      \ /          |      
   /|\       |    \|/    |      
    |        |     |   _\|/_
    |        |     |    /|\

ASCII dandelions have three parameters: Length of the stem (positive number between 1 and 256, number of seeds (positive number between 0 and 7), and orientation (^ or v). The above dandelions have for length, seeds and orientation, (3,5,^), (3,2,^), (2,3,^) and (3,7,v) respectively.

Seeds are filled in in the following order (flipped upside down for head-down dandelions), illustrated on a dandelion with length 2:

seeds:  0    1    2    3    4    5     6      7

             |   \ /  \|/  \ /  \|/  _\ /_  _\|/_
        |    |    |    |   /|\  /|\   /|\    /|\
        |    |    |    |    |    |     |      |

The Challenge:

Write a program/function which when given an ASCII dandelion as input, returns its length, seed count, and orientation formatted similarly to the above examples and when given parameters in that format returns an ASCII dandelion with those parameters. You can ignore the parenthesis and assume the input/output will be a number, a comma, a number, a comma, and either ^ or v. You may substitute other characters for ^/v so long as they can still be easily interpreted as 'up'/'down' (for example, u/d). You need not distinguish between dandelions that look the same, such as (2,1,^) and (3,0,^) or (2,1,^) and (2,1,v). Given the ASCII art, either set of parameters would be an acceptable output, and both sets of parameters can give the same ASCII art.

This is , so shortest code in bytes wins.


An example program in C# (not even slightly golfed):

    string Dandelion(string s)
    {
        if (s.Contains(','))
        {
            //got parameters as input
            string[] p = s.Split(',');
            //depth and width (number of seeds)
            int d = int.Parse(p[0]);
            int w = int.Parse(p[1]);
            //draw stem
            string art = "  |";
            while (d > 2)
            {
                d--;
                art += "\n  |";
            }
            //draw head
            string uhead = (w % 2 == 1 ? "|" : " ");
            string dhead = uhead;
            if (w > 1)
            {
                uhead = "\\" + uhead + "/";
                dhead = "/" + dhead + "\\";
                if (w > 5)
                {
                    uhead = "_" + uhead + "_\n /|\\";
                    dhead = "_\\|/_\n " + dhead;
                }
                else if (w > 3)
                {
                    uhead = " " + uhead + " \n /|\\";
                    dhead = " \\|/ \n " + dhead;
                }
                else
                {
                    uhead = " " + uhead + " \n  |";
                    dhead = "  |\n " + dhead;
                }
            }
            else
            {
                uhead = "  " + uhead + "\n  |";
                dhead = "  |\n  " + dhead;
            }
            //add head to body
            if (p[2] == "^")
            {
                return uhead + "\n" + art;
            }
            return art + "\n" + dhead;
        }
        else
        {
            //ASCII input
            string[] p = s.Split('\n');
            int l = p.Length - 1;
            int offset = 0;
            //find first non-' ' character in art
            while (p[0][offset] == ' ')
            {
                offset++;
            }
            int w = 0;
            if (p[0][offset] == '|')
            {
                //if '|', either head-down or no head.
                if (offset == 0 || p[l][offset - 1] == ' ')
                {
                    //if no space for a head to the left or no head at the bottom, no head.
                    return l.ToString() + ",1,^";
                }
                //head must have at least size 2, or else indistinguishable from no head case 
                w = 6;
                if (p[l][offset] == '|')
                {
                    //odd sized head
                    w = 7;
                }
                if (offset == 1 || p[l - 1][offset - 2] == ' ')
                {
                    //not size 6 or 7
                    w -= 2;
                    if (p[l - 1][offset - 1] == ' ')
                    {
                        //not size 4 or 5
                        w -= 2;
                    }
                }
                return l.ToString() + "," + w.ToString() + ",v";
            }
            else if (p[0][offset] == '\\')
            {
                //head at least size 2 and not 6/7, or indistinguishable from no head.
                w = 4;
                if (p[0][offset + 1] == '|')
                {
                    w = 5;
                }
                if (p[1][offset] == ' ')
                {
                    w -= 2;
                }
            }
            else
            {
                w = 6;
                if (p[0][offset + 2] == '|')
                {
                    w = 7;
                }
            }
            return l.ToString() + "," + w.ToString() + ",^";
        }
    }
\$\endgroup\$
12
  • \$\begingroup\$ Can we take some other distinct symbols instead of ^ and v? \$\endgroup\$
    – user41805
    Feb 6, 2017 at 19:00
  • \$\begingroup\$ @KritixiLithos So long as they can be easily interpreted as 'up' and 'down', sure. \$\endgroup\$
    – P...
    Feb 6, 2017 at 19:01
  • 3
    \$\begingroup\$ How do you find the difference between a length 2 seed 1 and a length 3 seed 0 dandelion? For seeds 0 and 1 it is also impossible to tell if they're flipped... \$\endgroup\$
    – Luke
    Feb 6, 2017 at 19:01
  • \$\begingroup\$ @Luke You need not distinguish between trees that look the same. You should return the same ASCII art in the case of length 2 seed 1 as in length 3 seed 0, and can return either length 2 seed 1 or length 3 seed 0 when that art is the input. \$\endgroup\$
    – P...
    Feb 6, 2017 at 19:05
  • 1
    \$\begingroup\$ Unless I'm mistaken, it seems like we have an answer that translates from parameters to ASCII and another answer that translates from ASCII to parameters. But we're supposed to support both tasks, right? \$\endgroup\$
    – Arnauld
    Feb 6, 2017 at 22:39

3 Answers 3

6
\$\begingroup\$

Bean, 321 bytes

Accepts input as single string in stdin without trailing newline. Parameters will be taken in the same manner, but formatted as

length (1-256)
orientation (u or d)
seeds (0-7)

The output parameters of the program when input is a dandelion will be in the same format as above.

Hexdump:

00000000 26 52 ca c1 20 5d d3 d0 80 d5 cd a0 5e 80 4c cc  &RÊÁ ]ÓÐ.ÕÍ ^.LÌ
00000010 a0 45 86 25 3e 88 4d a0 6b 80 4c a0 5e 80 23 60   E.%>.M k.L ^.#`
00000020 cd a0 63 80 43 cd a0 5f 80 50 84 a3 81 00 20 5e  Í c.CÍ _.P.£.. ^
00000030 d0 84 a3 81 01 4d a0 60 80 4a c1 4c a0 45 86 25  Ð.£..M `.JÁL E.%
00000040 3a d0 84 a3 81 02 4c a0 45 92 25 3a d0 84 a3 81  :Ð.£..L E.%:Ð.£.
00000050 03 20 60 a0 5f a3 81 04 cd a0 61 80 50 84 a3 81  . ` _£..Í a.P.£.
00000060 05 20 5e cf 52 cc a0 45 86 25 3c a3 81 06 23 81  . ^ÏRÌ E.%<£..#.
00000070 07 a0 61 cf 53 d0 80 a3 81 08 20 80 b5 4c a0 43  . aÏSÐ.£.. .µL C
00000080 8c 25 3a 00 52 a0 6b d3 50 80 a0 63 20 80 7e 20  .%:.R kÓP. c .~ 
00000090 63 20 80 7b 23 00 53 d0 80 c3 cc d0 80 a0 78 20  c .{#.SÐ.ÃÌÐ. x 
000000a0 80 01 8c 25 3a d2 ce cc a0 5d 80 23 81 09 80 4c  ...%:ÒÎÌ ].#...L
000000b0 d0 84 a0 5e 25 3b 81 23 81 0a ce d3 50 80 a0 78  Ð. ^%;.#..ÎÓP. x
000000c0 20 80 7e 81 23 60 23 71 cc d2 cc d0 84 d0 84 a0   .~.#`#qÌÒÌÐ.Ð. 
000000d0 78 25 3a 25 3a 81 23 81 0b cc a5 3d 8b 4c cc d0  x%:%:.#..Ì¥=.LÌÐ
000000e0 84 d0 84 a0 78 25 39 25 39 81 50 84 d0 84 a0 78  .Ð. x%9%9.P.Ð. x
000000f0 25 3a 25 39 8d 25 3b 4c cc d0 84 d0 84 a0 78 25  %:%9.%;LÌÐ.Ð. x%
00000100 39 25 3c 81 23 81 0b 8d 25 3b 8b 4c d0 84 d0 84  9%<.#...%;.LÐ.Ð.
00000110 a0 78 25 39 25 3b 81 23 81 0b 00 20 80 7b 23 81   x%9%;.#... .{#.
00000120 04 a0 df 20 a0 5c a0 7c a0 2f 0a a0 a0 5f af fc  . ß  \ | /.  _¯ü
00000130 5c a0 fc 20 8a a0 a0 fc a0 20 a0 a0 fc a0 20 7c  \ ü .  ü    ü  |
00000140 20                                                
00000141

Equivalent JavaScript:

+a?                               // if input is parameters
  (
    b=(C>5)<<(o=b=="d"),          // encoding if seeds > 5 and if orientation is down
    g=[                           // storing dandelion as array of characters
      c=" _ "[b],                 // "_" if seeds > 5 and orientation is up, else " "
      " \\"[d=+(C>1)],            // "\" if seeds > 1, else " "
      " |"[C&1],                  // "|" if seeds is odd, else " "
      " /"[d],
      c,                          // "_" if seeds > 5 and orientation is up, else " "
      "\n",
      e="  _"[b],                 // "_" if seeds > 5 and orientation is down, else " "
      ...(                        // spread characters for .reverse() to be correct
        C>3?                      // if seeds > 3 "/|\" else " | "
          "/|\\":
          " | "
      ),
      e,                          // "_" if seeds > 5 and orientation is down, else " "
      ..."\n  |  ".repeat(A-1)    // repeat stem length - 1 times
    ],
    o?                            // if orientation is down, reverse
      g.reverse():
      g
  ).join(""):                     // join array of characters
  [                               // else if input is dandelion
    _.length-1,                   // length of stem is number of rows - 1
    a=="  |  "||b[2]!="|"?        // test orientation of dandelion
      _.reverse()&&"d":           // reverse rows if necessary and return "d" for down
      "u"                         // else return "u" for up
    ,
    (
      _[1][1]!=" "?               // if 1,1 is not " ", seeds is 4 or more
        4+(_[0][0]!=_[1][0])*2:   // if 0,0 or 1,0 is "_", seeds is 6 or 7
        (_[0][3]!=" ")*2          // if 0,3 is not " ", seeds is 2 or 3
    )+
    (_[0][2]!=" ")                // if 0,2 is not " ", seeds is odd
  ].join("\n")                    // join parameters with newline to match input format

Implicitly takes stdin as newline separated array of unformatted strings in _ and implicitly outputs the parameters as a triplet. Test suite below and demo here:

const js = String.raw`
+a?                               // if input is parameters
  (
    b=(C>5)<<(o=b=="d"),          // encoding if seeds > 5 and if orientation is down
    g=[                           // storing dandelion as array of characters
      c=" _ "[b],                 // "_" if seeds > 5 and orientation is up, else " "
      " \\"[d=+(C>1)],            // "\" if seeds > 1, else " "
      " |"[C&1],                  // "|" if seeds is odd, else " "
      " /"[d],
      c,                          // "_" if seeds > 5 and orientation is up, else " "
      "\n",
      e="  _"[b],                 // "_" if seeds > 5 and orientation is down, else " "
      ...(                        // spread characters for .reverse() to be correct
        C>3?                      // if seeds > 3 "/|\" else " | "
          "/|\\":
          " | "
      ),
      e,                          // "_" if seeds > 5 and orientation is down, else " "
      ..."\n  |  ".repeat(A-1)    // repeat stem length - 1 times
    ],
    o?                            // if orientation is down, reverse
      g.reverse():
      g
  ).join(""):                     // join array of characters
  [                               // else if input is dandelion
    _.length-1,                   // length of stem is number of rows - 1
    a=="  |  "||b[2]!="|"?        // test orientation of dandelion
      _.reverse()&&"d":           // reverse rows if necessary and return "d" for down
      "u"                         // else return "u" for up
    ,
    (
      _[1][1]!=" "?               // if 1,1 is not " ", seeds is 4 or more
        4+(_[0][0]!=_[1][0])*2:   // if 0,0 or 1,0 is "_", seeds is 6 or 7
        (_[0][3]!=" ")*2          // if 0,3 is not " ", seeds is 2 or 3
    )+
    (_[0][2]!=" ")                // if 0,2 is not " ", seeds is odd
  ].join("\n")                    // join parameters with newline to match input format`;

// bean binary
const bin = bean.compile(js);

// program as function
const prog = bean.program(bin);

(document.body.onchange = function () {
  const parameters = stem.value + '\n' + orientation.value + '\n' + seeds.value;
  dandelion.textContent = prog(parameters);
  params.value = prog(dandelion.textContent);
})();
textarea {
  resize: none;
}
<script src="https://cdn.rawgit.com/patrickroberts/bean/master/dst/bean.min.js"></script>
<input id=stem type=number min=1 max=256 value=5>
<select id=orientation>
  <option value="u">u</option>
  <option value="d">d</option>
</select>
<input id=seeds type=number min=0 max=7 value=5>
<p>Dandelion (output from program given parameters)</p>
<pre id=dandelion></pre>
<p>Parameters (output from program given dandelion)</p>
<textarea id=params rows=3></textarea>

\$\endgroup\$
2
\$\begingroup\$

Javascript 513 391 379 355 bytes

Thanks to @Neil for helping golf off 134 bytes and @Kritixi Lithos for helping golf off 13 bytes This program assumes that any ASCII dandelions it is trying to identify have a line width of 5 for all lines of the string. ie: the stem is 2 spaces, the vertical line then another 2 spaces. (It can not classify dandelions it creates due to this issue)

(x,y,z)=>{a=Array(x+1).fill(1);if(x.length>1){a=x.split`
`;h=a.length-1;t=b=i=0;for(;i<(h>1)+1;i++)for(j=0;j<5;a[h-i][j++]!=' '&&b++)a[i][j]!=' '&&t++;return[h,(t>b?t:b)-(h>1),t>b?'^':'v']}z<'v'?(a[0]=y&4?y-2:y,a[1]=y&4?7:1):(a[x-1]=1+(y>4)*2+(y>4)*(y&2),a[x]=y&1+(y>2)*6);return a.map(n=>',  |, \\ /, \\|/,_\\ /_,_\\|/_, / \\, /|\\'.split`,`[n]).join`
`}

How it Works

The function checks if the first argument it is given has a length >1 (is a string). If the first argument is a string, it identifies the details of the ASCII dandelion.

To get the height of the dandelion, it splits the string around newline characters and counts the number of elements - 1. To get the number of seeds, it counts the number of non space characters on the top two and bottom two lines. if there are more characters in the top, it is declared to be upright and it uses the top count-1, otherwise it is declared to be upside down and uses the bottom count-1. If the total height is only 2, it determines uprightness by checking the counts of each line individually and choosing the side with more non space characters.

Otherwise, the function uses bitwise math in order to assign values from 0 to 7 according to the shape of each level of the dandelion to be drawn before converting each level into the appropriate string.

0:  
1:  |  
2: \\ /  
3: \\|/  
4:_\\ /_  
5:_\\|/_  
6: / \\  
7: /|\\

Try it online

\$\endgroup\$
7
  • 1
    \$\begingroup\$ @JonathanAllan fixed it so that it will now categorise a dandelion input \$\endgroup\$ Feb 7, 2017 at 2:04
  • 1
    \$\begingroup\$ Taking just your dandelion creator, I was then able to golf 125 bytes off. My code can't be directly pasted back into your solution, but maybe you can incorporate some of the savings: (x,y,z,a=[...Array(x+1)].fill(1))=>a.map(n=>', |, \\ /, \\|/,_\\ //,_\\|/_, / \\, /|\\'.split`,`[n],z<'v'?(a[0]=y&4?y-2:y,a[1]=y&4?7:1):(a[x-1]=1+(y>4)*2+(y>4)*(y&2),a[x]=y&1+(y>2)*6)).join`\n` \$\endgroup\$
    – Neil
    Feb 7, 2017 at 9:59
  • 1
    \$\begingroup\$ You can remove the else because you return in the if part anyway. Also while I'm here, I just wanted to point out that some functions such as split and join don't need the ()s when you invoke them on `-quoted string literals, which is why I didn't include them in my previous comment. \$\endgroup\$
    – Neil
    Feb 8, 2017 at 1:24
  • 1
    \$\begingroup\$ You have to use the right sort of quotes, it only works with `s, not 's or "s. \$\endgroup\$
    – Neil
    Feb 8, 2017 at 8:40
  • 1
    \$\begingroup\$ You can change the \n in join`\n` to a newline (as in the character). Also you can change the (h>2?1:0) to just h>2 and the (h>2?2:1) to (h>2)+1. tio.run/#IRiKF \$\endgroup\$
    – user41805
    Feb 8, 2017 at 14:28
1
\$\begingroup\$

Python 3.6, 476 453 448 413 394 bytes

Solution :

def h(i):
 l,s,o=i.split(",");s=int(s);z=["  |  "];q=(int(l)-1)*z;b,d,f,h,g,c,a=["  ","\\/"][s>1]+["  ","\\/"][s>3]+["| ","||"][s%2==1]+[" ","_"][s>5]
 if"d"==o:b,d,h,f,c,g=f,h,d,b,g,c
 r=[[a+b+c+d+a]+[" "+h+g+f+" "],z][s==0];return"\n".join([q+r,r+q]["u"==o])
def j(i):
 if","in i:print(h(i))
 else:[print(f"{m},{j},{k}")for m in range(257)for j in range(8)for k in"ud"if i==h(f"{m},{j},{k}")]

Result

>>> j("6,5,u")
 \|/
 /|\
  |
  |
  |
  |
  |
>>> j("5,2,d")
  |
  |
  |
  |
  |
 / \
>>> j("3,2,u")
 \ /
  |
  |
  |
>>> j("_\|/_\n /|\ \n  |  \n  |  \n  |  \n  |  \n  |  ")
6,7,u
>>> j(" \|/ \n /|\ \n  |  \n  |  \n  |  \n  |  ")
5,5,u
>>> j("  |  \n  |  \n  |  \n  |  \n  |  ")
4,1,u
4,1,d
5,0,u
5,0,d

Unfold

def g(i):
    def h(i):                       # this function draw dandelion
        l, s, o = i.split(",")      # split argument 
        s = int(s)

        # Calcul the string in the flower for up case 
        #   _\|/_   --> abcdb  --> when s=7 we have a=_ b=\ c=| d=/ h=/ g=| f=\ 
        #    /|\    -->  hgf  
        a = "_" if s > 5 else " "
        b = "\\" if s > 1 else " "
        d = "/" if s > 1 else " "
        h = "/" if s > 3 else " "
        f = "\\" if s > 3 else " "
        c = "|" if s%2 == 1 else " "
        g = "|" if s%2 == 1 else "|"

        # Shuffle a bit if the position is down 
        if"d"==o:
            b,d,h,f,c,g=f,h,d,b,g,c

        # treate the case to remove the line with ony white space
        if s==0:
            res=["  |  "]
        else:
            # assemble all piece of the flower
            res += [a+b+c+d+a]
            res += [" "+h+g+f+" "]

        # add stem up or down
        if o=="u":
            res = res + (int(l)-1) * ["  |  "]
        else:
            res = (int(l)-1) * ["  |  "] + res
        return "\n".join(res)

    if "," in i:
        print(h(i))
    else:
        # search in all flower posibility if we can recreate the input
        [print(m,j,k) for m in range(1, 257) for j in range(0, 8)for k in "ud"if i == h(f"{m},{j},{k}")]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.