33
\$\begingroup\$

This idea came to me when I saw my little brother playing with my calculator :D

The task

Taking a integer as an input, print that many graphical square roots under each other, like this:

n = 1

  ___
\/ 1


n = 3
    _______
   / _____
  / / ___
\/\/\/ 3


n = 5

      ___________
     / _________
    / / _______
   / / / _____
  / / / / ___
\/\/\/\/\/ 5


n = 10

           ______________________
          / ____________________
         / / __________________
        / / / ________________
       / / / / ______________
      / / / / / ____________
     / / / / / / __________
    / / / / / / / ________
   / / / / / / / / ______
  / / / / / / / / / ____
\/\/\/\/\/\/\/\/\/\/ 10

Each root consists of 4 parts, which I'm going to very scientifically name:

(s is the root size on the stack of roots, n is the input number, x is the number of digits)

  1. The "tail", which is a single \
  2. The "wall", which consists of / * s
  3. The "roof", which consists of _ * 2 * s + x
  4. And the number n under the smallest root, placed in the centre (leaving one empty space under the last _ in the smallest root)

Input

You must take input of the number n, no hardcoding the n

Output

The ascii roots your program made

This is a code-golf challenge, so lowest byte count for each language wins!

\$\endgroup\$
12
  • 3
    \$\begingroup\$ Will the number exceed the digit 9? \$\endgroup\$
    – user92069
    May 9, 2020 at 8:36
  • 2
    \$\begingroup\$ @Λ̸̸ good catch, will edit the rules. Yes, it can exceed the digit 9, updating the rules to clarify what to do \$\endgroup\$
    – Dion
    May 9, 2020 at 8:38
  • \$\begingroup\$ Related (the same idea, but different art) \$\endgroup\$ May 9, 2020 at 12:10
  • 21
    \$\begingroup\$ Why does the input have to be from STDIN and out to STDOUT? That seems like an unnecessarily arbitrary restriction. \$\endgroup\$
    – S.S. Anne
    May 9, 2020 at 14:12
  • 4
    \$\begingroup\$ @RossPresser Less interesting than you might think: with input s as a string, l = s.splitlines()[-1]; print(int(l[l.index(' '):]) ** (1 / l.count('/'))). \$\endgroup\$
    – Danica
    May 11, 2020 at 18:31

31 Answers 31

12
\$\begingroup\$

Python 2, 104 94 89 81 79 bytes

s=n=input()
while s:print' '*s,'/ '*(n-s)+'_'*(2*s+len(`n`));s-=1
print'\/'*n,n

Try it online!

Edit 1: Forgot I switched to python 2 lol

Edit 2: Thanks @ElPedro for the idea of switching to while loop!

Edit 3: Thanks @SurculoseSputum for saving 8 bytes!

Edit 4: Thanks @xnor for saving 2 bytes!

\$\endgroup\$
16
  • 1
    \$\begingroup\$ @Λ̸̸ XD my answer could probably be much shorter \$\endgroup\$
    – Dion
    May 9, 2020 at 9:03
  • 1
    \$\begingroup\$ You posted a minute before I did and mine is so similar that I'll delete and try to golf yours instead :) \$\endgroup\$
    – ElPedro
    May 9, 2020 at 9:09
  • 1
    \$\begingroup\$ @ElPedro yep, I saw your answer and remembered that i switched to python 2 for all of the savings) \$\endgroup\$
    – Dion
    May 9, 2020 at 9:10
  • 2
    \$\begingroup\$ @ElPedro 89 bytes :) \$\endgroup\$
    – Dion
    May 9, 2020 at 9:18
  • 4
    \$\begingroup\$ @Dion -~ bitwise negates (evaluated -1-x), then negates. This basically increments the number. You can take a look at this post. \$\endgroup\$
    – user92069
    May 9, 2020 at 9:47
11
\$\begingroup\$

JavaScript (ES6),  104 102  99 bytes

A recursive function starting with the last line and using regular expressions to update each line above.

f=(n,s='\\/'.repeat(n)+(e=' ')+n)=>~n?f(n-1,e+s.replace(/\\/g,e).replace(/.(?!.*\/)/g,'_'))+`
`+s:e

Try it online!

How?

Initialization

We generate the bottom line with:

s = '\\/'.repeat(n) + (e = ' ') + n

For instance, this gives "\/\/\/\/ 4" for \$n=4\$.

Recursion

We get rid of the backslashes with:

s.replace(/\\/g, e)

We create the 'roof' or increase its size with:

.replace(/.(?!.*\/)/g, '_')

which means: replace with an underscore each character that doesn't have any slash on its right.

This leads to:

 _________
 / _______
 / / _____
 / / / ___
\/\/\/\/ 4

And with a leading space inserted at each iteration:

     _________ 
    / _______ 
   / / _____ 
  / / / ___ 
\/\/\/\/ 4 
\$\endgroup\$
7
\$\begingroup\$

Erlang (escript), 188 bytes

f(0,N)->string:copies("\\/",N)++" "++integer_to_list(N);f(X,N)->string:copies(" ",X+1)++string:copies("/ ",N-X)++string:copies("_",2*X+floor(math:log10(N)+1))++"
"++f(X-1,N).
f(N)->f(N,N).

Try it online!

Explanation

f(N)->f(N,N).   % Assign the counter to the input.
f(X,N)->        % While the counter isn't 0:
string:copies(" ",X+1)
                %     Repeat the space counter + 1 times

++string:copies("/ ",N-X)
                %     Repeat "/ " input - counter times

++string:copies("_",
                %     Repeat the "_" that many times:

2*X             %     The counter doubled
+floor(math:log10(N)+1)
                %     Plus the length of the digit(s) of the input
++"
"               %     Join the above, and append a newline
++f(X-1,N).     %     Decrement the counter by 1

f(0,N)->        % If the counter turns into 0:
string:copies("\\/",N)
                %     Repeat "\/" input times

++" "           %     Append a space
++integer_to_list(N);
                %     Append the number converted into a string
```
\$\endgroup\$
0
6
\$\begingroup\$

Mathematica (Notebook) 30 bytes

Only in Spirit ;-)

Nest[Defer@√#&,#,#]&@Input[]

produces the nested radicals

enter image description here

in the spirit but not the letter of the problem.

Explanation

Input[]              //take input

Nest[f,expr,n]       //apply f to expr n times i.e. f[f[f[f[f....[expr]]..]] with n fs
Nest[f,#,#]&         //define a lambda that applies f to arg #, # times
Nest[f,#,#]&@Input[] //apply the lambda Nest[f,#,#]& to the value of Input[]


√#&                  //define a lambda that puts arg # inside √
Defer@√#&            //define a lambda that puts arg # inside √ buts keeps the mathematical square root unevaluated

Nest[Defer@√#&,#,#]&@Input[]
                     //apply the lambda Defer@√#& to Input, Input no of times 

\$\endgroup\$
5
\$\begingroup\$

05AB1E, 30 bytes

-4 bytes thanks to Kevin Cruijssen.

Lε-„/ ×'_y·¹g+׫y>ú}R„\/¹×¹‚ª»

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 𫹫 can be ¹‚ for -2 (» will join all inner lists by spaces before joining by newlines). And another -2 by changing >ðׄ/ ¹y-×'_y·¹g+×J to -„/ ×'_y·¹g+׫y>ú (the ¹y- has been golfed to - for -2, and the >ð× has been replaced with a trailing y>ú for the same byte-count). So combined it's 30 bytes. \$\endgroup\$ May 11, 2020 at 6:31
  • \$\begingroup\$ 29 bytes \$\endgroup\$ Mar 3, 2022 at 9:38
4
\$\begingroup\$

Pyth, 34 bytes

VQj*N"/ ",*hJ-QNd*+l`QyJ\_;jd,*"\/

Try it online!

VQ

Loop the variable N over 0 to Q (the input) minus 1

j*N"/ "

Join the following using N instances of "/ ":

,

The two element list of...

*hJ-QNd

... {Q - N + 1} space characters (d is the space character in Pyth). Store the value of Q minus N in the variable J so we can use it later.

*+l`QyJ\_

... {J times 2, plus the number of digits of Q} instances of the string "_"

;

End of loop

jd,*"\/

Join the following using a space:

  • Q instances of the string "\/"

  • Q casted to a string

Conveniently, the string literal is implicitly closed, and the two Qs are implicitly appended to the end of the program.

\$\endgroup\$
3
\$\begingroup\$

PowerShell, 88 84 bytes

param($n)1..$n|%{' '*($m=$n- --$_)+' /'*$_+' '+'_'*(2*$m+"$n".length)}
'\/'*$n+" $n"

Try it online!

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

Charcoal, 30 bytes

NηG↙η←⁺²Lθ↖η_Mη↘Pθ←←Fη«P↗⊕ι←/\

Try it online! Link is to verbose version of code. Explanation:

Nη

Input n as a number.

G↙η←⁺²Lθ↖η_

Print the "roof", ensuring that it is long enough to overhang n.

Mη↘Pθ←←

Print n as a string in the appropriate place.

Fη«

Loop n times.

P↗⊕ι

Print the next diagonal line of the "wall".

←/\

Print the next part of the "tail".

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

MATL, 43 bytes

:P"@QZ"47Oh1X@qX"95GVn@E+Y"hh]'\/'1GX"0GVhh

Try it online!

First time I have used X", Y", Z" in the same answer!

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

Jelly, 36 bytes

DLṭ1j+1,-,2×Ɱ$“ “/ “_”ẋ"ⱮṚṄ€ȧ⁾\/ẋ,⁸K

A full program which prints the result.

Try it online!

How?

DLṭ1j+1,-,2×Ɱ$“ “/ “_”ẋ"ⱮṚṄ€ȧ⁾\/ẋ,⁸K - Main Link: integer, n
D                                    - digits (n)
 L                                   - length
  ṭ1                                 - tack to one
    j                                - join with (n)
             $                       - last two links as a monad - f(n):
      1,-,2                          -   [1,-1,2]
            Ɱ                        -   map across [1..n] with:
           ×                         -     multiplication
     +                               - add (left to each of right, vectorised)
              “ “/ “_”               - [' ', '/ ', '_']
                        Ɱ            - map across (the list of list of numbers) with:
                       "             -   zipped:
                      ẋ              -     repetition
                         Ṛ           - reverse
                          Ṅ€         - print each with trailing newlines
                            ȧ        - logical AND (with n) -> n
                             ⁾\/     - ['\', '/']
                                ẋ    - repeat (n times)
                                 ,⁸  - pair with n
                                   K - join with a space
                                     - implicit print
\$\endgroup\$
2
\$\begingroup\$

MathGolf, 32 bytes

{kî-⌠ *_£(∞k£+'_*û/ ï*\n}û\/k* k

Try it online.

Explanation:

{             # Loop the (implicit) input amount of times:
 k            #  Push the input-integer
  î-          #  Subtract the 1-based loop-index
    ⌠         #  + 2
      *       #  And repeat that many spaces
 _            #  Duplicate this string
  £           #  Pop and push its length
   (          #  + 1
    ∞         #  * 2
     k        #  Push the input-integer again
      £       #  Pop and push its length
       +      #  Add those two integers together
        '_*  '#  And repeat that many "_"
 û/           #  Push the 2-char string "/ "
    ï*        #  And repeat it the 0-based loop-index amount of times
 \            #  Then swap the top two strings on the stack
 n            #  And push a newline character
}û\/k*        # After the loop: repeat 2-char string "\/" the input amount of times
              # Push a space
 k            # And push the input-integer
              # (after which the stack is joined together and output implicitly)
\$\endgroup\$
2
\$\begingroup\$

Wolfram Mathematica 120 bytes

a=StringRepeat;b=Print;Input[];
b[a[" ",#+1],a["/ ",%-#],a["_",2#+IntegerLength[%]]]&/@Range[%,1,-1];b[a["\/",%]," ",%];

enter image description here

Explanation

StringRepeat[str,n]         
                      //creates a string with str repeated n times

a=StringRepeat            
                      //alias for StringRepeat

Print[expr1,expr2,...]    
                      //prints expr1, expr2,... on a newline without separation

b=Print  
                      //alias for Print

Input[] 
                      //gets user input, 

;
                      //Hide implicit output

%   
                      //last output

IntegerLength[n]
                      //no of digits in n in base 10

a[" ",#+1]            
                     //Make a lamba StringRepeat with arg #, that prints " ",#+1 times

b[a[" ",#+1],a["/ ",%-#],a["_",2#+IntegerLength[%]]]& 

                     //Make a lambda with arg # that
                     //prints the appropriate "     /_________" 
                     //depending on #

b[....]&/@Range[%,1,-1]; 
                     //map the lambda b[....] over {%,%-1,%-2,...,1}

b[a["\/",%]," ",%]; 
                     //print the last row "\/\/\/...\/ "

Link to notebook

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

C# (Visual C# Interactive Compiler), 217 154 bytes

n=>Join("",Range(0,n).Select(i=>new S(' ',n-i+1)+new S('/',i*2)+new S('_',(n-i)*2-~(n+"").Length)+'\n').Concat(Repeat("\\/",n))).Replace("//", "/ ")+" "+n

Try it online!

Edit: Removed 19 bytes thanks to @KevinCruijssen, and used the header better(?)

\$\endgroup\$
2
  • \$\begingroup\$ Hi, welcome to CGCC! Unless you use it as a recursive function, you don't need to count the Func<int,string>f= and trailing ; in your byte-count. You can move those to your head & footer of your TIO-link. :) Also, (n+i-n)*2 is basically i*2. And n/10 is incorrect I'm afraid for \$n\geq100\$. This should be (n+"").Length() instead. In that case, you can also golf the (n-i)*2+1+(n+"").Length() to (n-i)*2-~(n+"").Length() (relevant tip). In total, it'll become 198 bytes. Enjoy your stay! :) \$\endgroup\$ May 11, 2020 at 9:36
  • \$\begingroup\$ @KevinCruijssen Thanks for the comment! And the tips. I saw others but their printing code in the footer, but I didn't know how much, or what, was okay to put in the header/footer. I added your suggestions, and some usings to my answer, do you think it's still acceptable? \$\endgroup\$
    – Netråm
    May 11, 2020 at 15:30
2
\$\begingroup\$

Haskell, 129 bytes

x%s=[1..x]>>s
0#b=b%"\\/"++' ':show b
x#b=(x+1)%" "++(b-x)%"/ "++(show b>>"_")++x%"__"++'\n':(x-1)#b
f x=x#x
main=interact$f.read

Try it online!

Ties the existing 129 byte answer but is compliant with the challenge by performing full IO.

\$\endgroup\$
1
\$\begingroup\$

Retina 0.8.2, 77 bytes

^
$.'$*_=$'$*/¶$'$*V 
/
=$.%'$*=¶  $.%'$* $`
=
__
(_+)(/+)
$2$1
/
/ 
V
\/
1A`

Try it online! Explanation:

^
$.'$*_=$'$*/¶$'$*V 

Insert some working elements: enough _s to cover the input, a / for each input, then on the next line, a V for each input (representing \/) and a space.

/
=$.%'$*=¶  $.%'$* $`

Now expand the /s into a bottom right triangle, and also add extra _s to overhang on both sides on each line.

=
__

Expand the =s which were placeholders for two _s.

(_+)(/+)
$2$1

Move the input cover next to the rest of the overhang.

/
/ 

Space the /s apart.

V
\/

Expand the Vs on the last line.

1A`

Delete some left-overs.

\$\endgroup\$
1
\$\begingroup\$

Haskell, 129 bytes

r=replicate
c=(concat.).r
f n|s<-show n=unlines$map(\o->r(n-o+1)' '++c o"/ "++r(2*(n-o)+length s)'_')[0..n-1]++[c n"\\/"++" "++s]

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This challenge has a restricted IO scheme, which does not permit functions. In order for this to be a valid answer you are expected to write a main declaration. \$\endgroup\$
    – Wheat Wizard
    May 11, 2020 at 23:27
1
\$\begingroup\$

Java 11, 137 124 bytes

n->{String l="\\/".repeat(n)+" "+n,r=l;for(;n-->0;r=l+"\n"+r)l=" "+l.replace('\\',' ').replaceAll(".(?!.*/)","_");return r;}

-13 bytes by porting @Arnauld's JavaScript answer, so make sure to upvote him!

Try it online.

Explanation:

n->{                       // Method with integer parameter and String return-type
  String l=                //  Temp-String `l` for the current line, starting at:
           "\\/".repeat(n) //   The input amount of "\/"
           +" "+n,         //   appended with a space and the input
         r=l;              //  Result-String, starting at this (last) line
  for(;n-->0               //  Loop `n` amount of times:
      ;                    //    After every iteration:
       r=l+"\n"+r)         //     Prepend the new `l` with newline to the result-String
    l=                     //   Change `l` to the new line:
      " "                  //    A space
      +l                   //    appended with the current line, with the replacements:
        .replace('\\',' ') //     All '\' replaced with spaces
        .replaceAll(".(?!.*/)","_");
                           //     And all characters NOT followed by a '/' with a "_"
  return r;}               //  And return the result-String after the loop
\$\endgroup\$
1
\$\begingroup\$

Julia, 107 bytes

n=parse(Int,readline())
println.([[" "^(s+1)*"/ "^(n-s)*"_"^(2s+length("$n")) for s=n:-1:1];"\\/"^n*" $n"])

Try it online!

Breakdown

n = parse(Int, readline())
println.([ # broadcasting with `.` applies `println` to each element of vector
    [
        " "^(s + 1)*"/ "^(n - s)*"_"^(2s + length("$n"))
        for s ∈ n:-1:1 # array comprehension
    ];   # semicolon enables blockmatrix-style array syntax...
         # ...which unpacks elements in array above into elements of vector
    "\\/"^n*" $n" # last element of vector
])
\$\endgroup\$
1
\$\begingroup\$

Python 3, 100, 99 bytes

n=int(input())
for i in range(n):print(" "*(n+~i)," /"*i,"_"*(2*n-2*i+len(str(n))))
print("\/"*n,n)

Try it online!

thnx to @KevinCruijssen for -1

\$\endgroup\$
1
1
\$\begingroup\$

Perl 5 -ap, 86 bytes

$\=$/.'\\/'x$_." $_";$_=$"x($_+1).'_'x(2*$_+y///c);for$a(1.."@F"-1){say;s, /| __,/ ,g}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Nice answer, pretty short too considering the length of a lot of the other answers, you can save a little bit more with some re-ordering and a couple of other tweaks though!: Try it online! \$\endgroup\$ Jul 26, 2020 at 11:32
1
\$\begingroup\$

CJam, 46 bytes

li:A:B;{A)S*"/ "BA-*'_2A*Bs,+*NA(:A}g"\\/"B*SB

Try it online!

Port of my Python answer

Explanation:

li            take input as integer
:A:B;         assign that to the variables A and B
{             start of while A loop
A)S*          push A-1 spaces
"/ "BA-*      push B-A strings of "/ "
'_2A*Bs,+*    push 2A + the number of digits _
N             push a newline
A(:A          decrement A
}g            end of while loop
"\\/"B*       push B \/
SB            push B after a space
\$\endgroup\$
1
\$\begingroup\$

Haskell, 122 bytes

x%y=[1..x]>>y
f x|n<-read x=unlines[(n+1-i)%" "++i%"/ "++(n-i)%"__"++(x>>"_")|i<-[0..n-1]]++n%"\\/"++' ':x
main=interact f

Try it online!

I've deliberately constrained myself to standard I/O. See my comments on the question.

\$\endgroup\$
1
\$\begingroup\$

Vyxal So, 30 bytes

ɾṘ›?ʀṪ‛/ *꘍?ɾd?L+\_*Ṙ+⁋,‛\/*$"

Try it Online!

This code's sorta backwards to reduce stack operations.

           ?ɾd                 # (1...input) * 2
              ?L+              # + log_10(input)
                 \_*           # That many underscores for each
                    Ṙ+         # Reverse that, and append to...
ɾṘ›                            # (2...input+1) reversed
          ꘍                    # For each, that many spaces appended to each of... 
   ?ʀṪ                         # 0...input-2
      ‛/ *                     # For each, that many copies of "/ "

                      ⁋,       # Print that, joined on newlines
                        ‛\/*   # Input * "\/"
                            $" # Paired with input
                               # (So flags) print that joined by a space
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 96 bytes

sub f{$n=pop;join"\n",(map' 'x($x=1+$n-$_).'/ 'x$_.'_'x($x*2-2+length$n),0..$n-1),'\/'x$n." $n"}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

PHP, 121 bytes

for($x=($i=$j=$argn)/10+1,$f=str_repeat;$i;$c.="/ ")printf("%{$i}s $c%s\n"," ",$f("_",2*$i--+$x));echo$f("\\/",$j)." $j";

Try it online!

This is not that great maybe, but I came with this.

\$\endgroup\$
0
\$\begingroup\$

Pyth, 54 44 bytes

VQ+d++*-QNd*"/ "N*+*2-QNl+""Q"_";++*"\/"hNdQ

Try it online!

edit 1: Thanks @mathjunkie for saving 10 bytes!

\$\endgroup\$
1
  • \$\begingroup\$ A few tips: FNrZ can be replaced by V. Each of the space literals (" ") can be replaced by d. Anywhere that you use +1 you can use h instead \$\endgroup\$ May 19, 2020 at 14:42
0
\$\begingroup\$

Pip, 38 bytes

Fi,aP[sYsXa-i"/ "Xi'_Ma.y.y]"\/"Xa.s.a

Try it online!

Explanation

This is one of those very rare occasions in Pip when a for loop seems to be the shortest solution.

Fi,aP[sYsXa-i"/ "Xi'_Ma.y.y]"\/"Xa.s.a
                                        s is space; a is 1st command-line arg (implicit)
Fi,a                                    For i in range(a):
    P                                    Print, with a newline
     [                     ]             the contents of this list, implicitly concatenated:
      s                                   A space
        sXa-i                             Space, repeated (a-i) times
       Y                                   also, yank that string into the y variable
             "/ "Xi                       "/ ", repeated (i) times
                      a.y.y               Concatenate a with y twice
                   '_M                     and replace each character with an underscore,
                                           giving a string of len(a) + 2 * (a-i) underscores
                            "\/"Xa      "\/", repeated (a) times
                                  .s    concatenated to space
                                    .a  concatenated to a
                                        Autoprint (implicit)
\$\endgroup\$
0
\$\begingroup\$

MAWP, 138 bytes

%@![1A~!~]%![!!!1M[84W;1A]%\A[95W2M;84W;1A]%2W1M3A{3M[29W1M5W;1A]25W;%1A}]~!!0/[25WP~1M~]%\1A3M[29W1M5W;1A]25W;%[99W25WM1M;95W2M;1A]%84W;:

Works as expected for single digit numbers, but beyond that, the last root will be longer than the others.

Try it!

\$\endgroup\$
0
\$\begingroup\$

Scala, 91 bytes

n=>print(n.to(1,-1).map{i=>" "*(i+1)+"/ "*(n-i)+"_"*(2*i+1)}:+("\\/"*n+" "+n)mkString "\n")

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Husk, 46 bytes

`:§+*"¦/"o:' s¹z+mR' ṫ¹m§+*" /"(:' R'_+L¹D≠¹)ŀ

Try it online!

\$\endgroup\$

Your Answer

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

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