Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
x, y = y, x. Понимаете, когда я, собеседуя человека, на вопрос о сложности алгоритма получаю ответ, что алгоритм не сложный… Мне кажется это сразу отказ!
К тому же я сделал скидку на волнение кандидата и свой кривой английский, и переформулировал вопрос несколько раз.
Неужели так сложно выучив и поняв новый алгоритм еще заодно запомнить как он называется?
Такое гденить на олимпиаде или соревновании по программированию,
int sum(int *m,int count,int s) //s играет роль локальной переменной, минус одна строка
{
for(int i=1;i<count;i++)
if(m[i]<m[0]) s+=m[0]-m[i];
else return s+sum(&m[i],count-i,0);
return 0;
}
int m[]={1,5,3,3,5,2,1,8};
int s=sum(m,sizeof(m)/sizeof(int),0);



f =: 3 : '>. /> +/ each (<@((-.@((i.@{.@I. , (({:@I.) + i.@(# - {:@I.))) (4 : ''1 x } y'') ]))@(1&>) # ]))("1) (-/~) y'
f 2 5 1 2 3 4 7 7 6
10
f 2 5 1 3 1 2 1 7 7 6
17
w =: 0 5 3 5 1 2 NB. исходные данные
s =: >./\ - [ NB. функция для подсчёта "дыр" слева-направо.
+/ (f w) <. f&.|. w
NB. >. - это поиск максимума.
NB. / - это between, т.е. вставка максимума между всеми элементами списка - т.е. по сути поиск глобального максимума.
NB. но если мы пишем /\ - то это between, но с сохранением промежуточных результатов, т.е. бегущий максимум. >./ w это 5, а >./\ w это 0 5 5 5 5 5 . всё отлично, но только данный подход считает так, как будто стены нет слева, а вот справа есть. для этого ниже делается реверс.
NB. &. - это применение одной функции, потом глагола, потом инверсной.
NB. |. - revers списка.
NB. т.е. f&.|. w - это будет: развернуть список, потом применить к нему f, а потом ещё раз развернуть. т.е. в данном случае, чтобы подсчитать впадины справа налево.
NB. в итоге: считаем дырки слева направо, потом справа-налево и берём меньшие значение для каждой дырки.
1 while s/([#-]) ( *)([#-])/\1-\2\3/g; $sum+=s/-/x/g;}END{say $sum
' task.txt #
# #
# # #
# # #
# # # #
## ## # #
##############
+/@(-~ >./\ <. >./\.) 2 5 1 3 1 2 1 7 7 6
17
«Достаточно неплохо, хотя ваше решение делает 2 прохода, но есть другой интересный алгоритм, который делает всего один проход».
var calculate = function( arr ){ // one cycle solution
var minMax,
sum = 0,
fullSum = 0,
el,
maxMax,
i, _i = arr.length - 1;
minMax = arr[0]; // first item is the current left max
maxMax = arr[_i]; // last item is the current right max
for( i = 0; i <= _i; i++ ){
el = arr[ i ];
if( minMax < el ){ // if the wall is getting higher
sum += ( el - minMax ) * i; //add rectangular currentHeight-lastHeight x distanceFromStart
fullSum += ( el - minMax ) * i; //add such rectangular to the whole avaliable free space
minMax = el;
}else{ // if we are getting down
fullSum += minMax - el; // add down delta to the whole avaliable free space sum
}
el = arr[ _i - i ];
if( maxMax < el ){ // same from the right side
sum += ( el - maxMax ) * i;
maxMax = el;
}
}
return fullSum - sum; // here we get whole avaliable space and reversed space that would be filled with water
};
// testing
[
[[0,0,0,10,0,0,0,0,0],0],
[[0,1,0,10,0,0,0,0,0],1],
[[1,0,1], 1],
[[5,0,5], 5],
[[0,1,0,1,0], 1],
[[1,0,1,0,1,0,1,0], 3],
[[1,0,1,0], 1],
[[1,0,1,2,0,2], 3],
[[2,5,1,2,3,4,7,7,6], 10],
[[5,1,0,1],1], //# thanks https://news.ycombinator.com/item?id=6640085
[[2,5,1,2,3,4,7,7,6,3,5], 12] //# thanks https://news.ycombinator.com/item?id=6640105
].forEach(function( el ){
if( calculate( el[0] ) !== el[1] ) throw( el );
});
use strict;
use warnings;
my @list = (2, 5, 1, 2, 3, 4, 7, 7, 6);
my $max = (sort { $a <=> $b } @list)[-1];
my $vol = 0;
for (my $y = $max; $y >= 0; $y--) {
my $left = 0;
my $right = 0;
for (my $x = 0; $x < @list; $x++) {
next if $list[$x] < $y;
$left = $x + 1;
last;
}
for (my $x = $#list; $x > $left; $x--) {
next if $list[$x] < $y;
$right = $x - 1;
last;
}
for (my $x = $left; $x < $right; $x++) {
$vol++ if $list[$x] < $y;
}
}
print "Volume = $vol\n";
use strict;
use warnings;
my @list = (2, 5, 1, 2, 3, 4, 7, 7, 6);
my $max = (sort { $a <=> $b } @list)[-1];
my $vol = 0;
my $y = 1;
while(1) {
my ($left, $right);
my $linevol = 0;
for (@list) {
if (!$left && $_ >= $y) {
$left = 1;
next;
}
if ($left && $_ >= $y) {
$vol += $linevol;
$linevol = 0;
$right = 1;
next;
}
$linevol++ if $left && $_ < $y;
}
last unless $right;
$y++;
}
print "Volume = $vol\n";
use strict;
use warnings;
my @list = (2, 5, 1, 2, 3, 4, 7, 7, 6);
my $vol = 0;
my $y = 1;
my $do = 1;
while($do) {
$do = 0;
my $linevol = 0;
for (my $x = 1; $x < @list; $x++) {
next if $list[$x - 1] < $y;
if ($list[$x] < $y) {
$list[$x] = $y;
$linevol++;
next;
}
$vol += $linevol;
$linevol = 0;
$do = 1;
}
$y++;
}
print "Volume = $vol\n";
use strict;
use warnings;
my @list = (2, 5, 1, 2, 3, 4, 7, 7, 6);
my @copy = @list;
my $vol = 0;
my $tmpvol = 0;
for (my $x = 1; $x < @copy; $x++) {
if ($copy[$x] < $copy[$x - 1]) {
$tmpvol += $copy[$x - 1] - $copy[$x];
$copy[$x] = $copy[$x - 1];
next;
}
$vol += $tmpvol;
$tmpvol = 0;
}
my $level = 0;
if ($tmpvol) {
for (my $x = @list - 1; $x > 0; $x--) {
last if $list[$x] >= $copy[$x];
$level = $list[$x] if $list[$x] > $level;
$tmpvol -= $copy[$x] - $level;
}
$vol += $tmpvol;
}
print "Volume = $vol\n";
На следующий день я показал эту задачу знакомому аспиранту, занимающемуся теоретическим computer science. После 40 минут размышлений у него также ничего не получилось.О боже…
function calculateBulb($heights) {
$started = false;
$start_max = 0;
$end_max = 0;
$water = 0;
$c = count($heights);
for($i = 0; $i < $c; $i++) {
if($i<1) {
continue;
}
if($i>7) {
break;
}
if(!$started) {
if($start_max <= $heights[$i]) {
$start_max = $heights[$i];
continue;
}
if($start_max > $heights[i]) {
$started = true;
$water += ($start_max - $heights[$i]);
}
} else if($heights[$i] >= $start_max) {
continue;
} else {
$water += ($start_max - $heights[$i]);
}
}
return $water;
}
$heights = [2,5,1,2,3,4,7,7,6];
echo(calculateBulb($heights)); // 10
$heights = [2,5,1,3,1,2,1,7,7,6];
echo(calculateBulb($heights)); // 17
$heights = [2,5,1,3,8,2,1,7,7,6];
echo(calculateBulb($heights)); // 13
[2,5,1,3,8,2,1,7,7,6];
[2,5,5,5,8,7,7,7,7,6];
[0,0,4,2,0,5,6,0,0,0];
...
else if($heights[$i] >= $start_max) {
$start_max = $heights[$i];
continue;
}
...
land = [2, 5, 1, 3, 1, 7, 1, 7, 2, 3, 2, 6]
data = {}
result = 0
for index, height in enumerate(land):
for level in xrange(1, height + 1):
result += index - data.get(level, index)
data[level] = index + 1
print result
double area(double X[],int N){
double S=0;
for(int a=0,b=N-1;a<b;){
double ha=X[a],hb=X[b];
if(ha<hb) while(X[++a]<ha) S+=ha-X[a];
else while(X[--b]<hb) S+=hb-X[b];
}
return S;
}
for(int a=0,b=N-1;a<b;) {...}
int a=0,b=N-1;
while(a<b) {...}
int a=0,b=N-1,S=0;
field = [" 1 ",
" 1 1 ",
"1 11 1 1 ",
"1 111 1 11",
"111111111111"]
def process(row):
i = 0
##print row,
for c in row:
if c == '1':
break
i = i+1
##print ", i=", i,
j = len(row)
for c in row[::-1]:
if c == '1':
break
j = j-1
##print ", j=", j
while i < j:
if row[i] == ' ':
row=row[:i]+'-'+row[i+1:]
i = i+1
print row
for row in field:
process(row)
private static int calc(int[] arr) {
int h = 0;
int w = 0;
int stone = 0;
int lake = 0;
for (int i = 1; i < arr.length; i++) {
if (h == 0) {
if (arr[i] < arr[i - 1]) {
h = arr[i - 1];
stone = arr[i];
w = 1;
}
} else {
if (arr[i] < h) {
stone += arr[i];
w++;
} else {
lake = w * h - stone;
}
}
}
return lake;
}
line = [2, 5, 1, 3, 1, 2, 1, 7, 7, 6]
S = 0
D = 0
M = line[0]
for k in line[1:]:
if k >= M:
M = k
S += D
D = 0
if M > k: D += M - k
print('S=', S)
line = [5, 1, 3, 1, 3]
S = 0
Len = len(line)
if Len > 2:
D = 0
Max = line[0]
Max2 = 0
Idx = 0
Idx2 = 0
for k in xrange(1, Len):
if line[k] >= Max:
Max = line[k]
Max2 = 0
S += D
D = 0
Idx = k
Idx2 = Idx
if Max > line[k]:
D += Max - line[k]
if Max2 <= line[k]:
Max2 = line[k]
Idx2 = k
if D > 0:
S = S+D-(Max-Max2)*(Idx2-Idx)
print('S=', S)
line = [5, 4, 3, 2, 1]
S = 0
Len = len(line)
if Len > 2:
D = 0
Max = line[0]
Max2 = 0
Idx = 0
Idx2 = 0
Sum2 = 0
for k in xrange(1,Len):
if line[k] >= Max:
Max = line[k]
Max2 = 0
S += D
D = 0
Idx = k
Idx2 = Idx
if Max > line[k]:
D += Max - line[k]
if Max2 <= line[k]:
Max2 = line[k]
Idx2 = k
Sum2 = 0
else: Sum2 += Max - line[k]
if D > 0 and (Idx2-Idx) > 1: S = S+D-(Max-Max2)*(Idx2-Idx) - Sum2
print('S=', S)
line = [2, 5, 1, 2, 3, 4, 7, 7, 7, 6, 6, 5, 2, 6]
S = 0
End = len(line)-1
if End > 1:
Df = 0
Dt = 0
Sf = 0
St = 0
MAXf = line[0]
MAXt = line[End]
IDXf = 0
IDXt = 0
k = 1
while k <= End and IDXf < End-IDXt:
if line[k] >= MAXf:
Sf += MAXf*(k-IDXf-1)-Df
MAXf = line[k]
Df = 0
IDXf = k
if MAXf > line[k]: Df += line[k]
if line[End-k] >= MAXt and IDXf != End-IDXt:
St += MAXt*(k-IDXt-1)-Dt
MAXt = line[End-k]
Dt = 0
IDXt = k
if MAXt > line[End-k]: Dt += line[End-k]
k += 1
S = Sf+St
print('S=', S)
function calcVolume(land) {
var r = land.length - 1, l = 0, rm = 0, lm = 0, v = 0;
while(l < r) {
lm = Math.max(land[l], lm);
rm = Math.max(land[r], rm);
v += lm >= rm ? rm - land[r--] : lm - land[l++];
}
return v;
}
public class Main {
public static void main(String[] args) {
System.out.println("Capacity: [10] = " + calculate(new int[]{2,5,1,2,3,4,7,7,6}));
System.out.println("Capacity: [17] = " + calculate(new int[]{2,5,1,3,1,2,1,7,7,6}));
System.out.println("Capacity: [42] = " + calculate(new int[]{4, 3, 1, 5, 8, 0, 4, 0 ,0 , 5, 5, 7, 5, 8, 3, 3}));
System.out.println("Capacity: [0] = " + calculate(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}));
System.out.println("Capacity: [0] = " + calculate(new int[]{0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}));
System.out.println("Capacity: [45] = " + calculate(new int[]{0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9}));
}
public static int calculate(int[] list) {
int cap = 0, firstVal = 0, tempCap = 0;
for (Integer val : list) {
if (val < firstVal) {
tempCap += firstVal - val;
continue;
}
cap += tempCap;
firstVal = val;
tempCap = 0;
}
return cap;
}
}
static void Main(string[] args)
{
Console.WriteLine(GetVolume(new int[] { 2, 5, 1, 2, 3, 4, 7, 7, 6 }));
Console.WriteLine(GetVolume(new int[] { 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 }));
Console.ReadKey();
}
static int GetVolume(int[] data)
{
var left = -1;
var right = -1;
var volume = 0;
var quantity = 0;
for (int i = 0, j = data.Length - 1; i <= j; i++, j--)
{
if (left == -1 && data[i] > data[i + 1]) left = i;
if (right == -1 && data[j] > data[j - 1]) right = j;
if (left != -1 && left != i)
{
volume += data[i];
quantity++;
}
if (i == j) break;
if (right != -1 && right != j)
{
volume += data[j];
quantity++;
}
}
return left == -1 || right == -1 ? 0 : (data[left] < data[right] ? data[left] : data[right]) * quantity - volume;
}
10
17
static void Main(string[] args)
{
var format = "Получилось: {0}, должно быть {1}";
Console.WriteLine(format, GetVolume(new int[] { 2, 5, 1, 2, 3, 4, 7, 7, 6 }), 10); //10
Console.WriteLine(format, GetVolume(new int[] { 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 }), 17); //17
Console.WriteLine(format, GetVolume(new int[] { 5, 4, 3, 2, 1 }), 0); //0
Console.WriteLine(format, GetVolume(new int[] { 1, 2, 3, 2, 5, 3, 4 }), 2); //2
Console.WriteLine(format, GetVolume(new int[] { 2, 7, 1, 1, 6, 2, 4, 1, 1, 2 }), 14); //14
Console.WriteLine(format, GetVolume(new int[] { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1 }), 1); //1
Console.ReadKey();
}
static int GetVolume(int[] data)
{
var leftTop = 0;
var rightTop = 0;
var volume = 0;
for (int i = 0, j = data.Length - 1; i < j; i++, j--)
{
if (data[i] > leftTop) leftTop = data[i];
if (data[j] > rightTop) rightTop = data[j];
if (leftTop >= rightTop)
{
i--;
volume += rightTop - data[j];
continue;
}
j++;
volume += leftTop - data[i];
}
return volume;
}
use strict;
use warnings;
print '1 ' . DoIt((0, 9, 8, 5, 1, 0, 1)) ."\n";
print '9 ' . DoIt((7, 1, 7, 2, 5)) ."\n";
print '10 ' . DoIt((2,5,1,2,3,4,7,7,6)) ."\n";
print '17 ' . DoIt((2,5,1,3,1,2,1,7,7,6)) ."\n";
print '42 ' . DoIt((4, 3, 1, 5, 8, 0, 4, 0 ,0 , 5, 5, 7, 5, 8, 3, 3)) ."\n";
sub DoIt {
my $pool = 0;
my $border = 0;
my $capacity = 0;
my $n = $#_ + 1;
foreach my $val (@_) {
$n --;
if ($val < $border) {
unless ($n <= 0) {
$pool += $border - $val;
next;
} else {
$pool = 0;
foreach my $rev_val (reverse @_) {
$pool += $val - $rev_val;
last if $rev_val < $val;
}
}
}
$border = $val;
$capacity += $pool;
$pool = 0;
}
return $capacity;
}
#!/usr/bin/perl
use strict;
use warnings;
print '10 ' . DoIt((2,5,1,2,3,4,7,7,6)) ."\n";
print '17 ' . DoIt((2,5,1,3,1,2,1,7,7,6)) ."\n";
print '42 ' . DoIt((4,3,1,5,8,0,4,0,0,5,5,7,5,8,3,3)) ."\n";
print '0 ' . DoIt((0,1,2,3,4,5,6,7,8,9,0)) ."\n";
print '0 ' . DoIt((0,9,8,7,6,5,4,3,2,1,0)) ."\n";
print '45 ' . DoIt((0,9,8,7,6,5,4,3,2,1,0,9)) ."\n";
print '1 ' . DoIt((0,9,8,7,6,5,4,3,2,1,0,1)) ."\n";
print '9 ' . DoIt((7,1,7,2,5)) ."\n";
print '2 ' . DoIt((1,0,7,0,1)) ."\n";
print '44 ' . DoIt((4,3,1,5,8,0,4,0,0,5,5,7,5,8,3,1,3,3)) ."\n";
sub DoIt {
my $pool = 0;
my $border = 0;
my $capacity = 0;
my $n = $#_ + 1;
foreach my $val (@_) {
$n --;
if ($val < $border && $n > 0) {
$pool += $border - $val;
next;
}
elsif ($val < $border && $n <= 0) {
$pool = 0;
foreach my $rev_val (reverse @_) {
$pool += $val - $rev_val if $rev_val < $val;
last if $rev_val > $val;
}
}
$border = $val;
$capacity += $pool;
$pool = 0;
}
return $capacity;
}
#include <cstddef>
#include <iostream>
template <std::size_t N>
int calc_volume(int const (&heights)[N])
{
int const max_height = 9;
int volume = 0;
int max_left_height = 0;
int prev_height = 0;
int tmp_volume[max_height + 1] = {};
for (int i = 0; i != N; ++i)
{
int const cur_height = heights[i];
if (cur_height > max_height)
return -1;
for (int j = prev_height; j < cur_height; ++j)
{
volume += tmp_volume[j];
tmp_volume[j] = 0;
}
for (int j = cur_height; j < max_left_height; ++j)
++tmp_volume[j];
if (cur_height > max_left_height)
max_left_height = cur_height;
prev_height = cur_height;
}
return volume;
}
int main()
{
int const heights1[] = { 2, 5, 1, 2, 3, 4, 7, 7, 6 }; // 10
int const heights2[] = { 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 }; // 17
int const heights3[] = { 2, 5, 1, 3, 8, 2, 1, 7, 7, 6 }; // 17
int const heights4[] = { 4, 3, 1, 5, 8, 0, 4, 0 ,0 , 5, 5, 7, 5, 8, 3, 3 }; // 42
int const heights5[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // 0
int const heights6[] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; // 0
int const heights7[] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9 }; // 45
int const heights8[] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1 }; // 1
int const heights9[] = { 7, 1, 7, 2, 5 }; // 9
int const vol = calc_volume(heights1);
std::cout << "volume: " << vol;
return 0;
}
water :: Integral a => [a] -> a
water vec = inwater 0 0 0 vec
where inwater ml mr ac vec
| length vec <= 1 = ac
| leftMax >= rightMax = inwater leftMax rightMax (ac + rightMax - last vec) (take (length vec - 1) vec)
| otherwise = inwater leftMax rightMax (ac + leftMax - head vec) (drop 1 vec)
where
leftMax = if head vec > ml then head vec else ml
rightMax = if last vec > mr then last vec else mr
main = putStrLn $ show $ water [2,5,1,3,1,2,1,7,5,6]
using namespace std;
typedef pair<int,int> intpair;
class comppair{
public:
bool operator()(const intpair &j1,const intpair &j2){
return j1.second>j2.second;
}
};
void Push(int *Arr,priority_queue<intpair,vector<intpair>,comppair> &Que,vector<bool> &V,int crd){
if(V[crd]) return;
V[crd]=true;
Que.push(intpair(crd,Arr[crd]));
}
int area(int *Arr,int M,int N){
if(N<3 || M<3) return 0;
vector<bool> Fill(M*N,true),Ready(M*N,false);
priority_queue<intpair,vector<intpair>,comppair> Que;
for(int i=0;i<M;i++){
Push(Arr,Que,Ready,i*N);
Push(Arr,Que,Ready,i*N+N-1);
}
for(int i=1;i<N-1;i++){
Push(Arr,Que,Ready,i);
Push(Arr,Que,Ready,N*(M-1)+i);
}
int smin=INT_MIN;
int res=0;
while(!Que.empty()){
intpair P=Que.top();
Que.pop();
int crd=P.first;
if(P.second>smin) smin=P.second;
else res+=smin-P.second;
int x=crd%N,y=crd/N;
if(x>0) Push(Arr,Que,Ready,crd-1);
if(x<N-1) Push(Arr,Que,Ready,crd+1);
if(y>0) Push(Arr,Que,Ready,crd-N);
if(y<M-1) Push(Arr,Que,Ready,crd+N);
Fill[crd]=false;
}
return res;
}
using namespace std;
typedef pair<int,int> intpair;
class comppair{
public:
bool operator()(const intpair &j1,const intpair &j2){
return j1.second>j2.second;
}
};
void Push(int *Arr,priority_queue<intpair,vector<intpair>,comppair> &Que,vector<bool> &V,int crd){
if(V[crd]) return;
V[crd]=true;
Que.push(intpair(crd,Arr[crd]));
}
int area(int *Arr,int NDim,int *Dim){
vector<int> Vol(NDim);
int V=1;
for(int i=0;i<NDim;i++){
if(Dim[i]<3) return 0;
Vol[i]=V;
V*=Dim[i];
}
vector<bool> Ready(V,false);
priority_queue<intpair,vector<intpair>,comppair> Que;
for(int i=0;i<V;i++){
bool qbnd=false;
for(int k=0;k<NDim;k++){
int x=(i/Vol[k])%Dim[k];
if(x==0 || x==Dim[k]-1){
qbnd=true; break;
}
}
if(qbnd) Push(Arr,Que,Ready,i);
}
int smin=INT_MIN;
int res=0;
while(!Que.empty()){
intpair P=Que.top();
Que.pop();
int crd=P.first;
if(P.second>smin) smin=P.second;
else res+=smin-P.second;
for(int k=0;k<NDim;k++){
int x=(crd/Vol[k])%Dim[k];
if(x!=0) Push(Arr,Que,Ready,crd-Vol[k]);
if(x!=Dim[k]-1) Push(Arr,Que,Ready,crd+Vol[k]);
}
}
return res;
}
<script>
console.clear();
var a =[], b =[]
,width =6
,h =12;
for(var i =0; i < width; i++)
a.push(Math.random() * h +1 |0), b.push(0);
//a=[9,0,10,9,10,0];
var c = 0;
for(var hh =1; hh < h +1; hh++){
var land =0
,lastC =0
,visL =[]; //visualLeft
for(var i =0; i < width; i++){
land = land || a[i] >= hh;
if(land && a[i] < hh){
c++;
lastC++;
visL.push(b[i]); //for visualize
b[i] = hh; //visualize
}
if(a[i] >= hh){
lastC =0;
visL =[];
}
}
c -= lastC;
while(lastC-- && lastC >=0) //for visualize
b[--i] = visL[lastC];
}
for(var j =0; j < h; j++){
var s ='';
for(var i =0; i < width; i++)
s += h - a[i] <= j ? 'M' : (h - b[i] <= j ?'.':'_');
console.log(s +' '+ (h - j) );
}
console.log('c = '+ c);
console.log('a = '+ a.join(','));
console.log('b = '+ b.join(','));
</script>
<script>
var width =6
,h =12
,a=[9,0,10,9,10,0] //c = 10 будет в консоли
,c = 0;
for(var hh =1; hh < h +1; hh++){
var land =0
,lastC =0;
for(var i =0; i < width; i++){
land = land || a[i] >= hh;
if(land && a[i] < hh){
c++;
lastC++;
}
if(a[i] >= hh)
lastC =0;
}
c -= lastC;
}
console.log('c = '+ c);
console.log('a = '+ a.join('\t,'));
</script>
Фиддл обоих вариантов: jsfiddle.net/spmbt/nhYtu/def pool(array, voda = 0):
row = [x-1 if x > 1 else 0 for x in array]
str_row = ''.join(['1' if x else '0' for x in row])
str_row = str_row[str_row.find('1'):str_row.rfind('1')]
cur_voda = str_row.count('0')
voda += cur_voda
if '1' in str_row:
return pool(row, voda)
return voda<source lang="python">
def pool(array):
voda = 0
while sum(array):
array = [x-1 if x > 1 else 0 for x in array]
str_row = ''.join(['1' if x else '0' for x in array])
str_row = str_row[str_row.find('1'):str_row.rfind('1')]
cur_voda = str_row.count('0')
voda += cur_voda
return voda
Как я завалил собеседование в Twitter