/ / Rekurzívny algoritmus alebo algoritmus plnenia plodín pre raster? - r, algoritmus, rekurzia, zaplavenie

Rekurzívny algoritmus alebo algoritmus plnenia plodín pre rastrový? - r, algoritmus, rekurzia, zaplavenie

Mám binárny raster takto:

101101
010111
101011
111101

Teraz musím urobiť tento riadok po riadku: Prejdite riadkom a počítajte priľahlé bunky, ktoré sú 1 (iba bunky v riadku!). A chcel by som získať vektor alebo niečo také. napríklad pre raster nad ním by:

1st row: 1 2 1

2nd row: 1 3

3rd row: 1 1 2

4th row: 4 1

Čítal som veľa o algoritme plnenia plnenia a tak ďalej. Ale nedokážem to spraviť správne.

Vyskúšal som tento rekurzívny algoritmus:

rec=function(x)
{if (x==0)
{return 0)
else return(1+rec(x+1))}

Ale to nefunguje.

odpovede:

0 pre odpoveď č. 1

Môžete sa pokúsiť použiť rle.

xy <- read.table(text = "1 0 1 1 0 1
0 1 0 1 1 1
1 0 1 0 1 1
1 1 1 1 0 1", sep = "")
xy

apply(xy, MARGIN = 1, FUN = function(x) {
x <- rle(x)
x$lengths[x$values == 1]
})

[[1]]
V2 V5
1  2  1

[[2]]
V3
1  3

[[3]]
V2 V4
1  1  2

[[4]]
V5
4  1

0 pre odpoveď č. 2

Nemáte potrebný algoritmus plnenia, ale nie je potrebná aj rekurzia.

Stačí počítať non-nuly. Najjednoduchší stavový stroj:

Starting state in the beginning of every line is 0
When state is 0 and you meet 1, remember X-position Start and make state 1
When state is 1 and you meet 0, make state 0 and add `Current - Start` to list
In other cases do nothing