arrays - Ruby: creating a matrix with diagonal band of 1,2,1 -
before start, plz understand total beginner @ ruby , computer programming, possess no prior knowledge , need programming basic of basic or else cannot understand. doing project school , stuck.
i have create code in ruby matrix n rows , n columns banded values [2,1]
[2,1,0,0,0] [1,2,1,0,0] [0,1,2,1,0] [0,0,1,2,1]
i made code dont know why wrong , where.. plz help!!
def make1d(n) = array.new(n) in 0..(n-1) a[i] = 0 end end def make2d(height,width) = array.new(height) in 0..(height-1) a[i] = make1d(width) end end def matrixa(n) a=make2d(n,n) k in 0..n-2 a[k][k]=2 a[k+1][k]=1 a[k][k+1]=1 a[n-1][n-1]=2 end end
ruby has great features can take advantage of. example, array.new
takes block (do ... end
) specify default value. block gets current index parameter (do |index| ... end
). perfect scenario!
your logic seems quite complex setting values on diagonal. if take step back, makes diagonal special if @ row , column indices? right, equal. if go 1 diagonal right/left, row , col indices off one, , on.
so here’s how write code:
array.new(n) |row| array.new(n) |col| case row - col when -1 1 when 0 2 when 1 1 else 0 end end end
or can make shorter, , handle general case. substitute 2
value want, or make function parameter
array.new(n) |row| array.new(n) |col| [2 - (row - col).abs, 0].max end end
Comments
Post a Comment