Re: elegant solution for counting runs
- From: Arjen Markus <arjen.markus@xxxxxxxxxx>
- Date: Sun, 30 Dec 2007 03:07:07 -0800 (PST)
On 30 dec, 09:34, Arjen Markus <arjen.mar...@xxxxxxxxxx> wrote:
On 30 dec, 02:24, analys...@xxxxxxxxxxx wrote:
This is not necessarily a fortran question but
I have a sequence of heads and tails and I want to count the number of
runs (of either kind) of length 1, 2,3,,,etc.
I spent a few hours on it and came up with a horrific solution that
has to test (within a loop through the sequence) for the first
observation , last observation and whether the last observation is a
run of length 1.
Surely theres a more elegant way and I would appreciate any hlep with
it.
I do not have a ready solution, but have you considered using the
cshift
function? I'd say, something like:
- Shift the array by 1 and check if the entries in the new array and
the
original match. If not, you have found a run of length 1. Keep the
entries that did match.
- Shift the array by 2 and check again, with the array of previous
matches.
The entries that don't match indicate runs of length 2 and so on.
Just a sketch, mind you. Hm, a nice puzzle ...
Regards,
Arjen
No, I retract that. Here is a small program that will count the
runs - I think it is fairly elegant, even though it loops over
the data explicitly:
! runs.f90 --
! COunt the runs of length 1, 2, ...
!
program count_runs
implicit none
integer, dimension(10) :: data = (/ 1, 0, 1, 1, 0, 0, 0, 1, 1,
0 /)
integer, dimension(10) :: runs
integer :: i
integer :: prev
integer :: count
runs = 0
count = 1
prev = data(1)
do i = 2,size(data)
if ( data(i) .ne. prev ) then
runs(count) = runs(count) + 1
prev = data(i)
count = 1
else
count = count + 1
endif
enddo
runs(count) = runs(count) + 1
write(*,*) runs
endprogram
(A solution with array operations like I sketched before should be
possible too, but this is very straightforward!)
Regards,
Arjen
.
- Follow-Ups:
- Re: elegant solution for counting runs
- From: analyst41
- Re: elegant solution for counting runs
- From: Lars Mossberg
- Re: elegant solution for counting runs
- From: David Frank
- Re: elegant solution for counting runs
- References:
- elegant solution for counting runs
- From: analyst41
- Re: elegant solution for counting runs
- From: Arjen Markus
- elegant solution for counting runs
- Prev by Date: Re: elegant solution for counting runs
- Next by Date: Re: elegant solution for counting runs
- Previous by thread: Re: elegant solution for counting runs
- Next by thread: Re: elegant solution for counting runs
- Index(es):
Relevant Pages
|