arrays - String padding and slicing to fixed length -


for random length array of 1's , 0's, need make start , end 001 , 100 respectively.

some examples in string form readability

"11010" => "00110100" "01010" => "0010100" "10000" => "00100" "01100" => "001100" "11111" => "001111100" "00100" => "00100" "00010" => "00100" "00000" => ""    # cases no 1's ignored 

the code came shift/unshift push/pops using until

def norm(arr)   (arr.index(1) > 2 ? arr.shift : arr.unshift(0)) until arr.index(1) == 2   (arr.rindex(1) > arr.length-3 ? arr.push(0) : arr.pop) until arr.rindex(1) == arr.length-3   arr end 

is there better(sort of?) way padding, slicing, etc.?

you can ignore 0 before first 1 , after last 1. so,

def norm(arr)   if arr.include?('1')     ['0', '0'] + arr.slice(arr.index('1')..arr.rindex('1')) + ['0', '0']   else     []   end end 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -