Water collected between towers: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Tailspin}}: update to stricter typing) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 44:
{{trans|Python}}
<
V l = tower.len
V highest_left = [0] [+] (1 .< l).map(n -> max(@tower[0 .< n]))
Line 66:
[6, 7, 10, 7, 6]]
print(towers.map(tower -> water_collected(tower)))</
{{out}}
Line 94:
=={{header|8080 Assembly}}==
<
jmp demo
;;; Calculate the amount of water a row of towers will hold
Line 198:
dw t6,t7-t6
dw t7,t_end-t7
dw 0</
{{out}}
Line 205:
=={{header|8086 Assembly}}==
<
org 100h
section .text
Line 286:
dw t6,t7-t6
dw t7,t_end-t7
dw 0</
{{out}}
Line 293:
=={{header|Action!}}==
<
BYTE i
Line 367:
Test(a6,4)
Test(a7,5)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Water_collected_between_towers.png Screenshot from Atari 8-bit computer]
Line 388:
=={{header|Ada}}==
<
procedure Water_Collected is
Line 461:
Show ((8, 7, 7, 6));
Show ((6, 7, 10, 7, 6));
end Water_Collected;</
{{out}}
Line 477:
{{Trans|JavaScript}}
<
-- waterCollected :: [Int] -> Int
Line 673:
return lst
end tell
end zipWith</
{{Out}}
<
=={{header|AutoHotkey}}==
<
topL := Max(oTwr*), l := num := 0, barCh := lbarCh := "", oLvl := []
while (++l <= topL)
Line 693:
}
return [num, barCh]
}</
Examples:<
,[5, 3, 7, 2, 6, 4, 5, 9, 1, 2]
,[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1]
Line 711:
result .= "Chart " inp " has " x.1 " water units`n" x.2 "------------------------`n"
}
MsgBox % result</
{{out}}
<pre>Chart [1, 5, 3, 7, 2] has 2 water units
Line 784:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f WATER_COLLECTED_BETWEEN_TOWERS.AWK [-v debug={0|1}]
BEGIN {
Line 816:
function max(x,y) { return((x > y) ? x : y) }
function min(x,y) { return((x < y) ? x : y) }
</syntaxhighlight>
{{out}}
<pre>
Line 829:
=={{header|BASIC}}==
<
20 K=K+1: READ N: IF N=0 THEN END
30 FOR I=0 TO N-1: READ T(I): NEXT
Line 848:
180 DATA 4, 8,7,7,6
190 DATA 5, 6,7,10,7,6
200 DATA 0</
{{out}}
Line 862:
=={{header|C}}==
Takes the integers as input from command line, prints out usage on incorrect invocation.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<stdio.h>
Line 934:
return 0;
}
</syntaxhighlight>
Output :
<pre>
Line 954:
===Version 1===
Translation from [[{{FULLPAGENAME}}#Visual_Basic_.NET|Visual Basic .NET]]. See that version 1 entry for code comment details and more sample output.
<
{
static void Main(string[] args)
Line 983:
}
}
}</
Block 2 retains 14 water units.
Block 3 retains 35 water units.
Line 989:
Block 5 retains 0 water units.
Block 6 retains 0 water units.
Block 7 retains 0 water units.</
===Version 2===
Conventional "scanning" algorithm, translated from [[{{FULLPAGENAME}}#Version_2_2|the second version of Visual Basic.NET]], but (intentionally tweaked to be) incapable of verbose output. See that version 2 entry for code comments and details.
<
{
// Variable names key:
Line 1,028:
}
}
}</
'''Output:'''
<pre>Block 1 holds 2 water units.
Line 1,039:
=={{header|C++}}==
<
#include <iostream>
#include <vector>
Line 1,103:
std::cin.get();
return 0;
}</
{{out}}
Line 1,117:
Similar two passes algorithm as many solutions here. First traverse left to right to find the highest tower on the left of each position, inclusive of the tower at the current position, than do the same to find the highest tower to the right of each position. Finally, compute the total water units held at any position as the difference of those two heights.
<
(defn trapped-water [towers]
(let [maxes #(reductions max %) ; the seq of increasing max values found in the input seq
Line 1,124:
mins (map min maxl maxr)] ; minimum highest surrounding tower per position
(reduce + (map - mins towers)))) ; sum up the trapped water per position
</syntaxhighlight>
{{out}}
<
;; in the following, # is a tower block and ~ is trapped water:
;;
Line 1,142:
;; 5 3 7 2 6 4 5 9 1 2
(trapped-water [5 3 7 2 6 4 5 9 1 2]) ;; 14
</syntaxhighlight>
=={{header|CLU}}==
<
where T has lt: proctype (T,T) returns (bool)
if a<b then return(b)
Line 1,195:
stream$puts(po, int$unparse(water(test)) || " ")
end
end start_up</
{{out}}
<pre>2 14 35 0 0 0 0</pre>
=={{header|Cowgol}}==
<
include "argv.coh";
Line 1,254:
print_i8(water(&towers[0], count as intptr));
print_nl();</
{{out}}
Line 1,275:
=={{header|D}}==
{{Trans|C#}}
<
void main() {
Line 1,323:
writeln(" water units.");
}
}</
{{out}}
Line 1,337:
Implements a version that uses recursion to solve the problem functionally, using two passes without requiring list reversal or modifications. On the list iteration from head to tail, gather the largest element seen so far (being the highest one on the left). Once the list is scanned, each position returns the highest tower to its right as reported by its follower, along with the amount of water seen so far, which can then be used to calculate the value at the current position. Back at the first list element, the final result is gathered.
<
-module(watertowers).
-export([towers/1, demo/0]).
Line 1,359:
[io:format("~p -> ~p~n", [Case, towers(Case)]) || Case <- Cases],
ok.
</syntaxhighlight>
{{out}}
Line 1,376:
=={{header|F_Sharp|F#}}==
see http://stackoverflow.com/questions/24414700/water-collected-between-towers/43779936#43779936 for an explanation of this code. It is proportional to the number of towers. Although the examples on stackoverflow claim this, the n they use is actually the distance between the two end towers and not the number of towers. Consider the case of a tower of height 5 at 1, a tower of height 10 at 39, and a tower of height 3 at 101.
<
(*
A solution I'd show to Euclid !!!!.
Line 1,390:
| _ -> l
fn (min n i) (max n i) g (e*(abs(n-i)-1))
</syntaxhighlight>
{{out}}
<pre>
Line 1,404:
=={{header|Factor}}==
<
: area ( seq -- n )
Line 1,417:
{ 8 7 7 6 }
{ 6 7 10 7 6 }
} [ dup area "%[%d, %] -> %d\n" printf ] each</
{{out}}
<pre>
Line 1,431:
=={{header|FreeBASIC}}==
Uses Nigel Galloway's very elegant idea, expressed verbosely so you can really see what's going on.
<
hght as uinteger
posi as uinteger
Line 1,494:
next j
print using "City configuration ## collected #### units of water."; i; water
next i</
{{out}}
<pre>City configuration 1 collected 2 units of water.
Line 1,505:
=={{header|Go}}==
<syntaxhighlight lang="go">
package main
Line 1,578:
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}</
{{out}}
Line 1,593:
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">
Integer waterBetweenTowers(List<Integer> towers) {
// iterate over the vertical axis. There the amount of water each row can hold is
Line 1,617:
println "$it => total water: ${waterBetweenTowers it}"
}
</syntaxhighlight>
{{out}}
Line 1,634:
Following the approach of slightly modified [http://stackoverflow.com/users/1416525/cdk cdk]'s Haskell solution at [http://stackoverflow.com/questions/24414700/amazon-water-collected-between-towers/ Stack Overflow]. As recommended in [http://h2.jaguarpaw.co.uk/posts/data-structures-matter/ Programming as if the Correct Data Structure (and Performance) Mattered] it uses [http://hackage.haskell.org/package/vector-0.12.0.1/docs/Data-Vector-Unboxed.html Vector] instead of Array:
<
import qualified Data.Vector.Unboxed as V
Line 1,657:
, [8, 7, 7, 6]
, [6, 7, 10, 7, 6]
]</
{{Out}}
<pre>2
Line 1,670:
Or, using Data.List for simplicity - no need to prioritize performance here - and adding diagrams:
<
-------------- WATER COLLECTED BETWEEN TOWERS ------------
Line 1,718:
showLegend =
((<>) . show . fmap fst)
<*> ((" -> " <>) . show . foldr ((+) . snd) 0)</
{{Out}}
<pre>
Line 1,801:
'''Solution:'''
<
waterLevels=: collectLevels - ] NB. water levels for each tower
collectedWater=: +/@waterLevels NB. sum the units of water collected
printTowers =: ' ' , [: |.@|: '#~' #~ ] ,. waterLevels NB. print a nice graph of towers and water</
'''Examples:'''
<
14
printTowers 5 3 7 2 6 4 5 9 1 2
Line 1,833:
TestResults =: 2 14 35 0 0 0 0
TestResults -: collectedWater &> TestTowers NB. check tests
1</
=={{header|Java}}==
{{trans|D}}
<
public static void main(String[] args) {
int i = 1;
Line 1,886:
}
}
}</
{{out}}
<pre>Block 1 holds 2 water units.
Line 1,900:
===ES5===
{{Trans|Haskell}}
<
'use strict';
Line 1,991:
//--> [2, 14, 35, 0, 0, 0, 0]
})();</
{{Out}}
<
===ES6===
{{Trans|Haskell}}
<
"use strict";
Line 2,131:
// MAIN ---
return main();
})();</
{{Out}}
<
=={{header|jq}}==
Line 2,140:
'''Works with gojq, the Go implementation of jq'''
<
. as $tower
| ($tower|length) as $n
Line 2,159:
towers[]
| "\(waterCollected) from \(.)"</
{{out}}
As for [[#Kotlin]] and others.
Line 2,165:
Inspired to [[#Python]].
<
function watercollected(towers::Vector{Int})
Line 2,208:
towerprint(towers, watercollected(towers))
println()
end</
{{out}}
Line 2,290:
=={{header|Kotlin}}==
{{trans|Python}}
<
fun waterCollected(tower: IntArray): Int {
Line 2,312:
println("${"%2d".format(waterCollected(tower))} from ${tower.contentToString()}")
}
}</
{{out}}
Line 2,327:
=={{header|Lua}}==
{{trans|C#}}
<
local length = 0
for _ in pairs(tower) do
Line 2,384:
end
main()</
{{out}}
<pre>Block 1 holds 2 water units.
Line 2,396:
=={{header|M2000 Interpreter}}==
===Scan min-max for each bar===
<syntaxhighlight lang="m2000 interpreter">
Module Water {
Flush ' empty stack
Line 2,428:
}
Water
</syntaxhighlight>
===Drain method===
Module Water2 {
Line 2,464:
}
Water2
<syntaxhighlight lang="m2000 interpreter">
</syntaxhighlight>
===Faster Method===
{{trans|AWK}}
<syntaxhighlight lang="m2000 interpreter">
Module Water3 {
Flush ' empty stack
Line 2,496:
}
Water3
</syntaxhighlight>
{{out}}
Line 2,504:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
waterbetween[h_List] := Module[{mi, ma, ch},
{mi, ma} = MinMax[h];
Line 2,521:
8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, {5, 5, 5, 5}, {5, 6, 7, 8}, {8,
7, 7, 6}, {6, 7, 10, 7, 6}};
waterbetween /@ h</
{{out}}
<pre>{2, 14, 35, 0, 0, 0, 0}</pre>
=={{header|Nim}}==
<
proc water(barChart: seq[int], isLeftPeak = false, isRightPeak = false): int =
Line 2,550:
const waterUnits = barCharts.map(chart=>water(chart, false, false))
echo(waterUnits)
</syntaxhighlight>
{{out}}
<pre>
Line 2,557:
=={{header|Perl}}==
<
use List::Util qw{ min max sum };
Line 2,579:
[ 8, 7, 7, 6 ],
[ 6, 7, 10, 7, 6 ],
);</
{{Out}}
<pre>2 14 35 0 0 0 0</pre>
Line 2,585:
=={{header|Phix}}==
=== inefficient one-pass method ===
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">collect_water</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">heights</span><span style="color: #0000FF;">)</span>
Line 2,610:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%35s : %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">),</span><span style="color: #000000;">collect_water</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 2,622:
</pre>
=== more efficient two-pass version ===
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">collect_water</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">heights</span><span style="color: #0000FF;">)</span>
Line 2,643:
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">diffs</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</
(same output)
=== pretty print routine ===
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (bugfix in p2js.js/$sidii(), 20/4/22)</span>
Line 2,671:
<span style="color: #000000;">print_water</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 2,688:
=={{header|Phixmonti}}==
{{trans|Phix}}
<
def collect_water
Line 2,714:
len for
get dup print " : " print collect_water ?
endfor</
{{out}}
<pre>[1, 5, 3, 7, 2] : 2
Line 2,727:
=={{header|PicoLisp}}==
<
(sum
'((A)
Line 2,744:
(5 6 7 8)
(8 7 7 6)
(6 7 10 7 6) ) ) )</
{{out}}
<pre>(2 14 35 0 0 0 0)</pre>
Line 2,751:
Based on the algorithm explained at [http://stackoverflow.com/questions/24414700/amazon-water-collected-between-towers/32135773#32135773 Stack Overflow]:
<
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
Line 2,773:
[6, 7, 10, 7, 6]]
[water_collected(tower) for tower in towers]</
{{Out}}
<pre>
Line 2,823:
Or, expressed in terms of '''itertools.accumulate''', and showing diagrams:
<
from itertools import accumulate
Line 2,940:
if __name__ == '__main__':
main()
</syntaxhighlight>
{{Out}}
<pre> █
Line 3,050:
=={{header|Racket}}==
<
(require racket/match)
Line 3,084:
[6 7 10 7 6]]))
(map water-collected-between-towers towerss))
(list 2 14 35 0 0 0 0)))</
When run produces no output -- meaning that the tests have run successfully.
Line 3,092:
{{Trans|Haskell}}
<syntaxhighlight lang="raku"
sub max_r ( @a ) { ([\max] @a.reverse).reverse }
Line 3,111:
[ 8, 7, 7, 6 ],
[ 6, 7, 10, 7, 6 ],
;</
{{Out}}
<pre>(2 14 35 0 0 0 0)</pre>
Line 3,117:
=={{header|REXX}}==
===version 1===
<
Call bars '1 5 3 7 2'
Call bars '5 3 7 2 6 4 5 9 1 2'
Line 3,182:
Say ol
End
Return</
{{out}}
<pre>1 5 3 7 2 -> 2
Line 3,248:
===version 2, simple numeric list output===
<
call tower 1 5 3 7 2
call tower 5 3 7 2 6 4 5 9 1 2
Line 3,270:
end /*f*/
say right(w.00, 9) 'units of rainwater collected for: ' y /*display water units.*/
return</
{{out|output|text= }}
<pre>
Line 3,286:
It tries to protect the aspect ratio by showing the buildings as in this task's preamble.
<
call tower 1 5 3 7 2
call tower 5 3 7 2 6 4 5 9 1 2
Line 3,320:
do z=t.0 by -1 to 0; say p.z /*display various tower floors & water.*/
end /*z*/
return</
{{out|output|text= }}
<pre>
Line 3,387:
=={{header|Ruby}}==
<
def a(array)
n=array.length
Line 3,422:
a([ 8, 7, 7, 6 ])
a([ 6, 7, 10, 7, 6 ])
return</
'''output'''
<pre>
Line 3,434:
=={{header|Rust}}==
<
use std::cmp::min;
Line 3,467:
}
}
</syntaxhighlight>
'''output'''
<pre>
Line 3,488:
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<
// Program to find maximum amount of water
Line 3,516:
println(s"Block ${barSet._2 + 1} could hold max. ${sqBoxWater(barSet._1)} units."))
}</
=={{header|Scheme}}==
<
(scheme write))
Line 3,552:
(5 6 7 8)
(8 7 7 6)
(6 7 10 7 6)))</
{{out}}
<pre>(1 5 3 7 2) -> 2
Line 3,567:
=={{header|Sidef}}==
<
gather { a.each {|e| take(m = max(m, e)) } }
}
Line 3,588:
[ 8, 7, 7, 6 ],
[ 6, 7, 10, 7, 6 ],
].map { water_collected(_) }.say</
{{out}}
<pre>
Line 3,595:
=={{header|Swift}}==
<
// https://stackoverflow.com/a/42821623
Line 3,628:
[6, 7, 10, 7, 6]] {
print("water collected = \(waterCollected(heights))")
}</
{{out}}
Line 3,642:
=={{header|Tailspin}}==
<
templates histogramWater
$ -> \( @: 0"1";
Line 3,665:
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]... -> '$ -> histogramWater; water in $;$#10;' -> !OUT::write
</syntaxhighlight>
{{out}}
Line 3,680:
=={{header|Tcl}}==
Tcl makes for a surprisingly short and readable implementation, next to some of the more functional-oriented languages.
<
proc flood {ground} {
Line 3,714:
} {
puts [flood $p]:\t$p
}</
{{out}}
Line 3,732:
The program can optionally display the interim string representation of each tower block before the final count is completed. I've since modified it to have the same block and wavy characters are the
[[{{FULLPAGENAME}}#version_3|REXX 9.3]] output, but used the double-wide columns, as pictured in the task definition area.
<
Module Module1
Sub Main(Args() As String)
Line 3,768:
Next
End Sub
End Module</
{{out}}<syntaxhighlight lang="text">Block 1 retains 2 water units.
Block 2 retains 14 water units.
Block 3 retains 35 water units.
Line 3,775:
Block 5 retains 0 water units.
Block 6 retains 0 water units.
Block 7 retains 0 water units.</
Verbose output shows towers with water ("Almost equal to" characters) left in the "wells" between towers. Just supply any command-line parameter to see it. Use no command line parameters to see the plain output above.
<syntaxhighlight lang="text"> ██
██
██≈≈██
Line 3,844:
██████████
██████████
Block 7 retains 0 water units.</
===Version 2===
'''Method:''' More conventional "scanning" method. A Char array is used, but no Replace() statements. Output is similar to version 1, although there is now a left margin of three spaces, the results statement is immediately to the right of the string representation of the tower blocks (instead of underneath), the verb is "hold(s)" instead of "retains", and there is a special string when the results indicate zero.
<
''' <summary>
''' wide - Widens the aspect ratio of a linefeed separated string.
Line 3,946:
Next
End Sub
End Module</
Regular version 2 output:
<syntaxhighlight lang="text"> Block 1 holds 2 water units.
Block 2 holds 14 water units.
Block 3 holds 35 water units.
Line 3,954:
Block 5 does not hold any water units.
Block 6 does not hold any water units.
Block 7 does not hold any water units.</
Sample of version 2 verbose output:
<syntaxhighlight lang="text"> ██
██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██
Line 3,969:
████████
████████
████████ Block 4 does not hold any water units.</
=={{header|Wren}}==
Line 3,975:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<
import "/fmt" for Fmt
Line 3,995:
[6, 7, 10, 7, 6]
]
for (tower in towers) Fmt.print("$2d from $n", waterCollected.call(tower), tower)</
{{out}}
Line 4,009:
=={{header|XPL0}}==
<
int Array, Width, Height, I, Row, Col, Left, Right, Water;
[Water:= 0; Height:= 0;
Line 4,041:
ChOut(0, ^ );
];
]</
{{out}}
Line 4,050:
=={{header|Yabasic}}==
{{trans|AWK}}
<
data "1,5,3,7,2", "5,3,7,2,6,4,5,9,1,2", "2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1"
data "5,5,5,5", "5,6,7,8", "8,7,7,6", "6,7,10,7,6"
Line 4,086:
next i
print ans," ",n$
end sub</
=={{header|zkl}}==
{{trans|Haskell}}
<
// compile max wall heights from left to right and right to left
// then each pair is left/right wall of that cell.
Line 4,103:
xs.reduce('wrap(s,x,a){ s=f(s,x); a.append(s); s },i,ss:=List());
ss
} // scanl((1,5,3,7,2),max,0) --> (1,5,5,7,7)</
<
T(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),
T(5, 5, 5, 5), T(5, 6, 7, 8),T(8, 7, 7, 6),
T(6, 7, 10, 7, 6) )
.pump(List, waterCollected).println();</
{{out}}
<pre>
|