while true
    n = gets.to_i
    break if n == 0
    m = gets.chomp.split.map(&:to_i)
    count, success = 0, false
    10000.times{
        if m == (1..m.length).to_a
            success = true
            break
        end
        m.map!{|x| x - 1}
        m << m.length
        m.delete(0)
        count += 1
    }
    puts success ? count : -1
end
