How to resolve the algorithm Munching squares step by step in the jq programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Munching squares step by step in the jq programming language
Table of Contents
Problem Statement
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Munching squares step by step in the jq programming language
Source code in the jq programming language
jq -n -r -f Munching_squares.jq > Munching_squares.svg
# Convert the input integer to an array of bits with lsb first
def integer_to_lsb:
[recurse(if . > 0 then ./2|floor else empty end) | . % 2] ;
# input array of bits (with lsb first) is converted to an integer
def lsb_to_integer:
reduce .[] as $bit
# state: [power, ans]
([1,0]; (.[0] * 2) as $b | [$b, .[1] + (.[0] * $bit)])
| .[1];
def xor(x;y):
def lxor(a;b): # a and/or b may be null
if a == 1 then if b==1 then 0 else 1 end
elif b==1 then if a==1 then 0 else 1 end
else 0
end;
(x|integer_to_lsb) as $s
| (y|integer_to_lsb) as $t
| ([$s|length, $t|length] | max) as $length
| reduce range(0;$length) as $i
([]; . + [ lxor($s[$i]; $t[$i]) ] )
| lsb_to_integer;
def rgb2rgb:
def p: (. + 0.5) | floor; # to nearest integer
"rgb(\(.red|p),\(.green|p),\(.blue|p))";
def svg(width; height):
"<svg width='\(width // "100%")' height='\(height // "100%")'
xmlns='http://www.w3.org/2000/svg'>";
def pixel(x; y; color):
(color | if type == "string" then . else rgb2rgb end) as $c
| "<circle r='1' cx='\(x)' cy='\(y)' fill='\($c)' />";
# rgb is a JSON object: { "red": _, "green": _, "blue": _}
def xor_pattern(width; height; rgb1; rgb2):
# create colour table
256 as $size
| (reduce range(0;$size) as $i
([]; . + [
{"red": (rgb1.red + (rgb2.red - rgb1.red) * $i / $size),
"green": (rgb1.green + (rgb2.green - rgb1.green) * $i / $size),
"blue": (rgb1.blue + (rgb2.blue - rgb1.blue) * $i / $size) }])
) as $colours
# create the image
| svg(width; height),
( (range(0;width) as $x
| range(0;height) as $y
| pixel($x; $y; $colours[ xor($x; $y) % $size] ) ) ),
"</svg>" ;
def black: { "red": 0, "green": 0, "blue": 0};
def red: black + { "red": 255 };
def yellow: red + { "green": 255 };
xor_pattern(384; 384; red; yellow)
You may also check:How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the Kotlin programming language
You may also check:How to resolve the algorithm RSA code step by step in the Perl programming language
You may also check:How to resolve the algorithm Program name step by step in the Go programming language
You may also check:How to resolve the algorithm Determine if only one instance is running step by step in the Python programming language
You may also check:How to resolve the algorithm Digital root step by step in the RPL programming language