Search code examples
loopsj

Print an equilateral triangle in J language


I a trying to print a equilateral triangle to the console screen. this is what I could find

]\ 'hello' NB. which prints
h
he
hel
hell
hello

Solution

  • First solution that I came up with is this:

       eq=. ('b< >' 8!:2 (] ,.~ |.@}."1)@:([: >:/~ i.)) 
       eq 5
        1    
       111   
      11111  
     1111111 
    111111111
       eq 10
             1         
            111        
           11111       
          1111111      
         111111111     
        11111111111    
       1111111111111   
      111111111111111  
     11111111111111111 
    1111111111111111111
    

    eq is a verb that first takes the argument and creates a matrix with the lower left of 1's using ([: >:/~ i.), this is then fed to (] ,.~ |.@}."1) which drops the first character of each line then reverses before appending to the original matrix. Finally, to get rid of the ugly 0's I use the foreign conjunction 8!:2 which formats the binary array into characters and the left argument 'b< >' specifies that 0's will be replaced with blank spaces.

    Second solution:

       eq2=: ([ ,.~ |.@}."1)@:(]\) 
       eq2 'hello'
        h    
       ehe   
      lehel  
     llehell 
    ollehello
       eq2 '*******'
          *      
         ***     
        *****    
       *******   
      *********  
     *********** 
    *************
    

    eq2 works the same way except it uses your ]\ initially which means that the format foreign conjunction is not necessary, as the result fed to ([ ,.~ |.@}."1) is already in character form.