Lazy Array

Asked at DatabricksOnsite

Reported by the problem's creator, not verified

Build LazyArray, a list of integers that records transformations and applies them only when a value is needed.

The constructor takes the starting values. An array is named by an integer handle: the starting array is handle 0, and every call to map creates a new array with the next handle (1, 2, ...) without changing any existing one.

A transformation is a string: "add:k", "sub:k" and "mul:k" apply + k, - k and * k to an element, and "neg" negates it. Each application of one transformation to one element is a call, and calls() returns how many calls have been made so far.

Each test drives one LazyArray(values) instance through a sequence of calls and checks every return value.

Examples

  1. Example 1

    Input: init = [[4,7,2,7,9]], operations = [["map",[0,"add:3"]],["map",[1,"mul:2"]],["calls",[]],["index_of",[2,20]],["calls",[]],["index_of",[0,7]],["calls",[]],["index_of",[2,99]],["calls",[]],["index_of",[1,5]],["calls",[]]]

    Output: [1,2,0,1,4,1,4,-1,14,2,17]

    Explanation: map only records operations, so calls() stays 0 after two maps. Array 2 is [4,7,2,7,9] plus 3, times 2, which is [14,20,10,10,24]. index_of(2, 20) looks at index 0 (2 calls, value 14) and index 1 (2 calls, value 20) and stops: 4 calls. index_of(0, 7) checks index 0 (4, no) and index 1 (7, yes) on the untouched original, with no calls. index_of(2, 99) evaluates all five elements with 2 calls each, 10 more calls, and finds nothing. Array 1 is [7,10,5,10,12], so index_of(1, 5) stops at index 2 after 3 elements, 3 calls.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.