64 bit ASCII weaving

18

2

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>

trichoplax

Posted 2015-07-31T13:23:27.810

Reputation: 10 499

Answers

10

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]
"||--||--"
"|--||--|"
"--||--||"
"-||--||-"
"||--||--"
"|--||--|"
"--||--||"
"-||--||-"

tmartin

Posted 2015-07-31T13:23:27.810

Reputation: 3 917

It really doesn't get simpler or more straightforward than this! – JohnE – 2015-07-31T18:37:41.183

1@JohnE That's only true for people who understand K. ;) – Alex A. – 2015-07-31T18:45:45.817

14

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.

Martin Ender

Posted 2015-07-31T13:23:27.810

Reputation: 184 808

2I applaud you :). This is probably the quickest answer in PPCG history – Beta Decay – 2015-07-31T13:28:43.730

7@BetaDecay The benefit of golfing languages is that you have less to type, so you can code faster. :P – Martin Ender – 2015-07-31T13:29:56.153

1Geez, even went to the trouble of editing the tags before answering! Somebody spends too much time golfing ;P – Sabre – 2015-07-31T14:02:25.060

Is this intended output: link

– Octavia Togami – 2015-08-01T23:38:30.207

@Kenzie that input number is bigger than 2^64-1. – Martin Ender – 2015-08-02T05:35:05.117

5

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])));
    }
}

ankh-morpork

Posted 2015-07-31T13:23:27.810

Reputation: 1 350

3I must say, I'm not used to being beaten by Java. :P Nice work. – Alex A. – 2015-07-31T23:50:21.573

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. – ankh-morpork – 2015-07-31T23:54:44.780

@Ypnypn that should definitely work – ankh-morpork – 2015-08-02T17:14:55.410

Wow, this is impressive. Good job. – TheNumberOne – 2015-08-03T01:02:51.947

4

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 =
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--

Luis Mendo

Posted 2015-07-31T13:23:27.810

Reputation: 87 464

de2bi will save you a few more characters ;-) – Hoki – 2015-07-31T15:46:19.223

@Hoki! Thanks! I thought about it... but it gives a different order of the result – Luis Mendo – 2015-07-31T16:52:42.533

yep, you have to reverse a='|-' to a='-|'. And use x=de2bi(typecast(W,'uint8'))+1; – Hoki – 2015-07-31T16:55:17.043

@Hoki I managed to fit de2bi just moving the 9- term (used for reversal). Thanks again! – Luis Mendo – 2015-07-31T17:07:15.743

3

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.

randomra

Posted 2015-07-31T13:23:27.810

Reputation: 19 909

3

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.

Alex A.

Posted 2015-07-31T13:23:27.810

Reputation: 23 761

3

CJam, 30 28 27 bytes

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

Try it online in the CJam interpreter.

Dennis

Posted 2015-07-31T13:23:27.810

Reputation: 196 637

2

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.

xnor

Posted 2015-07-31T13:23:27.810

Reputation: 115 687

1

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 */
}

Cole Cameron

Posted 2015-07-31T13:23:27.810

Reputation: 1 013

Could you format the title like "C, 100 bytes"? That way it'll show up in the leaderboard better. – Anubian Noob – 2015-07-31T17:31:23.947

Yes, sorry about that. – Cole Cameron – 2015-07-31T17:55:37.877

1I'm having trouble getting your code to run correctly on my environment. Are you compiling with any specific options? – ankh-morpork – 2015-07-31T22:08:38.077

@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 – Cole Cameron – 2015-08-01T04:10:20.400

Makes sense I tested on Ubuntu – ankh-morpork – 2015-08-01T10:35:34.070

1

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]

Kade

Posted 2015-07-31T13:23:27.810

Reputation: 7 463

1

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

Ypnypn

Posted 2015-07-31T13:23:27.810

Reputation: 10 485