Largest product in a grid: Difference between revisions

Content added Content deleted
No edit summary
Line 682: Line 682:
*/66 91 88 97
*/66 91 88 97
51267216</syntaxhighlight>
51267216</syntaxhighlight>

=={{header|jq}}==
'''Works with both jq and gojq, the C and Go implementations of jq'''

In Part 1 below, a simple solution to the basic problem, namely finding the
maximum value, is presented.

In Part 2, the focus shifts to reporting the location and direction of the
elements with the maximal product. Arrays are indexed from 0.

In both cases, it is assumed that `grid` has been defined as a
function returning the grid as an array of arrays as presented, for
example, in the [[#Wren|Wren]] entry.
'''Generic Utilities'''
<syntaxhighlight lang=jq>
def prod(s): reduce s as $x (1; . * $x);
def prod: prod(.[]);

# Input: an array
# Output: a stream of arrays
def windows($size): range(0; 1+length-$size) as $i | .[$i:$i+$size];
</syntaxhighlight>
===Part 1===
<syntaxhighlight lang=jq>
# Input: a matrix
def largest_product($size):
([.[] | (windows($size) | prod)] | max) as $rowmax
| ([transpose[] | (windows($size) | prod)] | max) as $colmax
| [$rowmax, $colmax]|max,
if ($rowmax > $colmax) then "The rows have it." else "The columns
have it." end ;

grid | largest_product(4)
</syntaxhighlight>
{{output}}
<pre>
51267216
The columns have it.
</pre>
===Part 2===
<syntaxhighlight lang=jq>
# Input: a row
# Output: [$i, $maxproduct]
def largest_product_of_row($size):
[range(0; 1 + length - $size) as $i
| [$i, (.[$i:$i+$size] | prod)] ] | max_by(.[1]);

# Input: a matrix
def largest_product_of_rows($size):
[range(0; length) as $row
| [$row, (.[$row] | largest_product_of_row($size)) ]] | max_by(.[1][1])
| [ .[0], .[1][]] ;

# Input: a matrix
def largest_product_with_details($size):
largest_product_of_rows($size) as [$row, $rowcol, $rmax]
| (transpose | largest_product_of_rows($size)) as [$col, $colrow, $cmax]
| if $rmax == $cmax
then "row-wise at \([$row, $rowcol]) equals col-wise at \([$col, $colrow]): \($cmax)"
elif $rmax > $cmax then "The rows have it at \([$row, $rowcol]): \($rmax)"
else "The columns have it at \([$colrow, $col]): \($cmax)"
end ;

grid | largest_product_with_details(4)
</syntaxhighlight>
{{output}}
<pre>
The columns have it at [6,15]: 51267216
</pre>


=={{header|Julia}}==
=={{header|Julia}}==