19
\$\begingroup\$

Input

Two integers:

  • A non-negative integer W in the range 0 to 2^64-1, specifying the weave.
  • A positive integer S in the range 1 to 255, specifying the side length.

These can be taken in whichever order suits you.

Output

An S by S ASCII representation of the requested weave (S newline separated strings of S characters with an optional trailing newline). The weave is defined by the weave number W as follows:

Convert W to binary and split into 8 bytes. The first (most significant) byte defines the top row, from left (most significant bit) to right. The next byte defines the next row, and so on for 8 rows. The weave number defines an 8 by 8 square which should be tiled over the required area starting from the top left. That is, its top left corner should correspond to the top left corner of the area to be covered.

Every 0 should be displayed as a | and every 1 should be displayed as a -

Examples

Input: 0 8

Ouput:

||||||||
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||

Input: 3703872701923249305 8

Output:

||--||--
|--||--|
--||--||
-||--||-
||--||--
|--||--|
--||--||
-||--||-

Input: 3732582711467756595 10

Output:

||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--

Input: 16141147355100479488 3

Output:

---
|||
---

Leaderboard Snippet

(using Martin's template)

var QUESTION_ID=54123;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>

\$\endgroup\$

11 Answers 11

13
\$\begingroup\$

CJam, 33 31 bytes

q~:X;2b64Te["|-"f=8/{X*X<z}2*N*

Test it here.

Explanation

q~      e# Read and eval input.
:X;     e# Store the side length in X and discard it.
2b      e# Convert to base 2.
64Te[   e# Left-pad to length 64 with zeroes.
"|-"f=  e# Select '|' for 0 and '=' for 1.
8/      e# Split into chunks of 8 bits.
{       e# Do the following twice:
  X*    e#   Repeat lines X times (to ensure we have enough of them).
  X<    e#   Truncate them to exactly X lines.
  z     e#   Transpose the grid.
        e#   The transpose ensures that the second pass tiles the columns, and that the
        e#   grid is oriented correctly again after both passes are done.
}2*
N*      e# Join lines by newline characters.
\$\endgroup\$
5
  • 2
    \$\begingroup\$ I applaud you :). This is probably the quickest answer in PPCG history \$\endgroup\$
    – Beta Decay
    Jul 31, 2015 at 13:28
  • 7
    \$\begingroup\$ @BetaDecay The benefit of golfing languages is that you have less to type, so you can code faster. :P \$\endgroup\$ Jul 31, 2015 at 13:29
  • 1
    \$\begingroup\$ Geez, even went to the trouble of editing the tags before answering! Somebody spends too much time golfing ;P \$\endgroup\$
    – Sabre
    Jul 31, 2015 at 14:02
  • \$\begingroup\$ Is this intended output: link \$\endgroup\$ Aug 1, 2015 at 23:38
  • \$\begingroup\$ @Kenzie that input number is bigger than 2^64-1. \$\endgroup\$ Aug 2, 2015 at 5:35
10
\$\begingroup\$

K, 20

{y#y#'"|-"8 8#0b\:x}

.

             0b\:x    // convert to binary
         8 8#         // reshape into an 8x8 boolean matrix
     "|-"             // index into this char vector using the booleans as indices  
  y#'                 // extend horizontally
y#                    // extend vertically

.

k){y#y#'"|-"8 8#0b\:x}[3703872701923249305j;10]
"||--||--||"
"|--||--||-"
"--||--||--"
"-||--||--|"
"||--||--||"
"|--||--||-"
"--||--||--"
"-||--||--|"
"||--||--||"
"|--||--||-"

k){y#y#'"|-"8 8#0b\:x}[3703872701923249305j;8]
"||--||--"
"|--||--|"
"--||--||"
"-||--||-"
"||--||--"
"|--||--|"
"--||--||"
"-||--||-"
\$\endgroup\$
2
  • \$\begingroup\$ It really doesn't get simpler or more straightforward than this! \$\endgroup\$
    – JohnE
    Jul 31, 2015 at 18:37
  • 1
    \$\begingroup\$ @JohnE That's only true for people who understand K. ;) \$\endgroup\$
    – Alex A.
    Jul 31, 2015 at 18:45
5
\$\begingroup\$

Java, 110 109 107 Bytes

My code is in the form of an anonymous lambda function that takes a long and an int then returns a String.

(w,s)->{String b="";for(int j,i=s--;i-->0;b+='\n')for(j=s;j>=0;)b+=(w>>8*(i%8)+j--%8)%2<1?'|':45;return b;}

Complete testable class

import java.util.function.BiFunction;
public class AsciiWeave {   
    public static void main(String[] args){
        BiFunction<Long,Integer,String> weave = 
            (w,s)->{String b="";for(int j,i=s--;i-->0;b+='\n')for(j=s;j>=0;)b+=(w>>8*(i%8)+j--%8)%2<1?'|':45;return b;}}
        ;
        System.out.println(weave.apply(Long.valueOf(args[0]),Integer.valueOf(args[1])));
    }
}
\$\endgroup\$
5
  • 3
    \$\begingroup\$ I must say, I'm not used to being beaten by Java. :P Nice work. \$\endgroup\$
    – Alex A.
    Jul 31, 2015 at 23:50
  • \$\begingroup\$ Thanks @AlexA.! Lambdas really make java more usable for golfing: (w,s)-> instead of String w(long w,int s) is a big save right off the bat. \$\endgroup\$ Jul 31, 2015 at 23:54
  • \$\begingroup\$ @Ypnypn that should definitely work \$\endgroup\$ Aug 2, 2015 at 17:14
  • \$\begingroup\$ Wow, this is impressive. Good job. \$\endgroup\$ Aug 3, 2015 at 1:02
  • \$\begingroup\$ 105 bytes \$\endgroup\$
    – ceilingcat
    Aug 3, 2020 at 5:05
4
\$\begingroup\$

Matlab, 86 80 bytes

function f(W,S)
a='|-';x=de2bi(typecast(W,'uint8'))+1;s=8-mod(0:S-1,8);a(x(s,s))

Thanks to Hoki for his suggestion, which led me to save me 6 bytes.

Example:

>> W = uint64(3732582711467756595)
W =
  3732582711467756595
>> S = uint8(10)
S =
   10
>> f(W,S)
ans =
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
\$\endgroup\$
4
  • \$\begingroup\$ de2bi will save you a few more characters ;-) \$\endgroup\$
    – Hoki
    Jul 31, 2015 at 15:46
  • \$\begingroup\$ @Hoki! Thanks! I thought about it... but it gives a different order of the result \$\endgroup\$
    – Luis Mendo
    Jul 31, 2015 at 16:52
  • \$\begingroup\$ yep, you have to reverse a='|-' to a='-|'. And use x=de2bi(typecast(W,'uint8'))+1; \$\endgroup\$
    – Hoki
    Jul 31, 2015 at 16:55
  • \$\begingroup\$ @Hoki I managed to fit de2bi just moving the 9- term (used for reversal). Thanks again! \$\endgroup\$
    – Luis Mendo
    Jul 31, 2015 at 17:07
3
\$\begingroup\$

Julia, 145 bytes

f(w,s)=(A=map(i->i=="1"?"-":"|",reshape(split(lpad(bin(w),64,0),""),8,8))';for i=1:s A=hcat(A,A)end;for i=1:s println(join(A[i>8?i%8:i,1:s]))end)

This creates a function that accepts two integers and prints to stdout.

Ungolfed + explanation:

function f(w,s)
    # Convert w to binary, left-padded with zeros to length 64
    b = lpad(bin(w), 64, 0)

    # Create an 8x8 array of | and -
    A = transpose(map(i -> i == "1" ? "-" : "|", reshape(split(b, ""), 8, 8)))

    # Horizontally concatenate A to itself s times
    for i = 1:s
        A = hcat(A, A)
    end

    # Print the rows of A, recycling as necessary
    for i = 1:s
        println(join(A[i > 8 ? i % 8 : i, 1:s]))
    end
end

This is pretty long and I'm sure it can be made much shorter. Working on it.

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

J, 28 bytes

'|-'{~]$"1]$8 8$_64{.#.inv@[

Usage:

   3732582711467756595 ('|-'{~]$"1]$8 8$_64{.#.inv@[) 10
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--

Explanation (right to left):

#.inv@[   binary representation vector of S
_64{.     padded with 0-s from the right to length 64
8 8$      reshaped in an 8 by 8 matrix
]$"1]$    tiled to a W by W size
'|-'{~    select | or - based on matrix element values

Try it online here.

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

CJam, 30 28 27 bytes

q~_2m*W%/ff{8f%8bm>"|-"=}N*

Try it online in the CJam interpreter.

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

Python, 77

lambda w,s:''.join('|-'[w>>~n/s%8*8+~n%s%8&1]+'\n'[~n%s:]for n in range(s*s))

For each of the s*s values of n:

  • Compute the coordinates via divmod (i,j)=(n/s,n%s)
  • Compute the location in the tiling as (i%8,j%8)
  • Compute the appropriate bit position as 8*(i%8)+(j%8)
  • Extract that bit of w by shifting w that many spaces with right and take the last bit with &1.
  • Join one of '|-' at that position
  • Add the newline at the end of every row whenever n%s==0

Actually, all that ends up getting the tiling backwards, since it reads w from the end. We fix this by using ~n in place of n. I tried a recursive approach instead, but it turned out slightly longer.

The expression w>>~n/s%8*8+~n%s%8&1 is a miracle of operator precedence.

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

Python 2, 132 Bytes

Certainly not the most elegant solution, and it's barely shorter than C, but it's a start.. Input is taken comma-separated.

k,n=input()
k=[`['|-'[int(x)]for x in'{0:064b}'.format(k)]`[2::5][i*8:i*8+8]*n for i in range(8)]*n
for j in range(n):print k[j][:n]
\$\endgroup\$
1
\$\begingroup\$

C, 160 135 bytes

i;main(s,v)char**v;{s=atoi(v[2]);for(;i++<s*s+s;)putchar(i%(s+1)?strtoull(v[1],0,10)&1ull<<63-(i/(s+1)*8+(i%(s+1)-1)%8)%64?45:'|':10);}

Some more golfing can be done here and need an explanation, but I don't have time at the moment :)

Ungolfed:

i;

main(s,v)
char**v;
{
    s=atoi(v[2]);
    for(;i++<s*s+s;)
        putchar(i%(s+1) ? /* print dash or pipe, unless at end of row, then print newline */
            /* Calculating which bit to check based on the position is the tough part */
            strtoull(v[1],0,10) & 1ull << 63-(i/(s+1)*8+(i%(s+1)-1)%8)%64 ? /* If bit at correct index is set, print dash, otherwise pipe */
                45 /* dash */
                : '|' /* pipe */
            : 10); /* newline */
}
\$\endgroup\$
5
  • \$\begingroup\$ Could you format the title like "C, 100 bytes"? That way it'll show up in the leaderboard better. \$\endgroup\$ Jul 31, 2015 at 17:31
  • \$\begingroup\$ Yes, sorry about that. \$\endgroup\$ Jul 31, 2015 at 17:55
  • 1
    \$\begingroup\$ I'm having trouble getting your code to run correctly on my environment. Are you compiling with any specific options? \$\endgroup\$ Jul 31, 2015 at 22:08
  • \$\begingroup\$ @dohaqatar7 It looks like some Linux environments require stdlib.h to be included explicitly. I wasn't forced to include it earlier when I tested on CentOS (I believe that's what I was on). Now on Ubuntu, I can't get it to run without compiling like so: gcc -include stdlib.h w.c \$\endgroup\$ Aug 1, 2015 at 4:10
  • \$\begingroup\$ Makes sense I tested on Ubuntu \$\endgroup\$ Aug 1, 2015 at 10:35
1
\$\begingroup\$

Pyth, 31 30 bytes

L<*QbQjbyyMcs@L"|-".[Z64jvz2 8

The input should be on two lines, W then S.

Try it here

Explanation

L                              # define y(b):
  *Qb                          #   b, repeated Q (the second input) times
 <   Q                         #   cut to length Q

                        jvz2   # convert the first input to binary
                   .[Z64       # pad with 0's to length 64
             @L"|-"            # map the digits to the appropriate character
            s                  # convert the list of characters to a string
           c                 8 # chop into 8 strings
         yM                    # extend each string to the correct size
        y                      # extend the list of strings to the correct size
      jb                       # join with newlines
\$\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.