I have an array of integers where I'm treating 0 in a special way. I need to manipulate the array so that the output is an array of the same size with all the zeros after all the non-zero values. For example:
input: [| 10; 5; 4; 0; 6; 0; 0; 0; 0 |]output: [| 10; 5; 4; 6; 0; 0; 0; 0; 0 |]
This is some code I got to work:
let a = [| 10; 5; 4; 0; 6; 0; 0; 0; 0 |] inlet l = List.filter (fun c -> c <> 0) (Array.to_list a) inlet cells i = if i <= List.length l - 1 then List.nth l i else 0 inArray.init (Array.length a) cells;;
I have a feeling that this solution could be improved by addressing:
- converting back and forth between lists and arrays. Is there a better way than calling
Array.to_list
and thenList.filter
to keep the order and exclude certain values? - accessing a list using
List.nth
which is O(i) for each position in the array. Is there a better way to use a list's values as the first source when populating an array?