Count consecutive elements in array

153 views
Skip to first unread message

Indi Kernick

unread,
Dec 15, 2017, 10:13:13 PM12/15/17
to Jsonnet
I hope this is the right place for a question like this.

I have an array of 0s and 1s. I like to count the number of consecutive 0s and 1s in the array and put this information into a new array. I’d like 1s to have a positive count and 0s to have a negative count. Here is an example of what I mean:

[1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1] -> [3, -1, 1, -2, 4]

I’m not very experienced with functional programming so I can’t figure out how to do this in Jsonnet. If anyone could help me out that would be greatly appreciated.

Love the language by the way!

Igor Peshansky

unread,
Dec 16, 2017, 9:18:14 PM12/16/17
to Indi Kernick, Jsonnet
Here's one quick-and-dirty example (loosely based on the std.uniq implementation):

local count_runs(arr) =
  local sign(b) =
    if b < 0 then -1 else if b > 0 then 1 else 0;
  local f(a, b) =
    local runs = a[0];
    local last = a[1];
    local i = if b == 1 then 1 else -1;
    if last == null then
      [runs, i]
    else if sign(last) == i then
      [runs, last + i]
    else
      [runs + [last], i];
    local r = std.foldl(f, arr, [[], null]);
    r[0] + [r[1]];

count_runs([1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1])

This produces your desired result:

[3, -1, 1, -2, 4]

I'm sure someone with more Jsonnet experience can come up with something shorter / more readable.

FYI, it's very useful to play around with the language interactively on the demo page.

Hope this helps,
        Igor


--
You received this message because you are subscribed to the Google Groups "Jsonnet" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jsonnet+unsubscribe@googlegroups.com.
To post to this group, send email to jso...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jsonnet/5dca377e-f209-4979-951e-6c8a6f952e67%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Indi Kernick

unread,
Dec 16, 2017, 10:06:35 PM12/16/17
to Jsonnet
Oh wow!

I didn't know that's what the foldl function was for. The foldl function can be used to iterate an array with seemingly mutable state that changes as the array is iterated. It's a for loop!!!

Thank you so much Igor.

You didn't just give me a snippet that I can copy-and-paste, you taught me something about functional programming!

BTW, is this the right place for questions like "How did I do x in Jsonnet?"?

Reply all
Reply to author
Forward
0 new messages