# Algorithm 1 â€¢

This note contains questions/puzzle and algorithms to answer these problems. Most of the codes in this type of note are in Python or JS.

## Count number of element in an array or properties of an object #

For example,

countTheNumberOfLines([1, [1]]) // returns 3countTheNumberOfLines({"x": 1, "y": [1]}) // returns 3
private countTheNumberOfLines(obj: any): number {  if (typeof obj === 'object') {    if (Array.isArray(obj)) {      let count = obj.length;      for (let i = 0; i < obj.length; i++) {        count += countTheNumberOfLines(obj[i]);      }      return count;    } else if (obj && typeof obj === 'object') {      let count = Object.keys(obj).length;      for (const key in obj) {        if (typeof obj[key] !== 'function') {          count += countTheNumberOfLines(obj[key]);        }      }      return count;    }    return 0;  }  return 0;}

## Make chunkers / windows #

Split a sequence into windows with size and slide.

def chunker(seq, size, slide=None, exact_size=False):    if slide is None:        slide = size    if exact_size:        return [seq[pos:pos + size] for pos in range(0, len(seq), slide) if len(seq[pos:pos + size]) == size]    else:        return [seq[pos:pos + size] for pos in range(0, len(seq), slide)]
seq = [i for i in range(10)]chunker(seq, 3)chunker(seq, 3, exact_size=True)chunker(seq, 3, slide=2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
[[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8], [8, 9]]


Make all arrays equal in size, filled with np.nan,

def chunker2(seq, size, slide=None):    if slide is None:        slide = size    return [np.append( seq[pos:pos + size], np.repeat(np.nan, size-len(seq[pos:pos + size])) )            for pos in range(0, len(seq), slide)]
seq = [i for i in range(10)]chunker2(seq, size=4, slide=2)
[array([0., 1., 2., 3.]),
array([2., 3., 4., 5.]),
array([4., 5., 6., 7.]),
array([6., 7., 8., 9.]),
array([ 8.,  9., nan, nan])]


## Plot a grid of squares #

Plot a square of NxN small other squares. Each one has a probability Pxi/N of being coloured, where i is the line where it stands.

N = 100P = 0.5im_size = 5image = np.repeat(np.array(range(1,N+1)).reshape(N, 1), N, axis=1)# LESS understandable but executing FASTERimage = (P/N * image) <= np.random.rand(N,N)# MORE understandable but executing SLOWERdef bernoulli(num, P, N):  return 1-np.random.binomial(1, P*num/N)vfunc = np.vectorize(bernoulli)image = vfunc(image, P, N)plt.figure(figsize=(im_size, im_size))plt.imshow(image, cmap='gray')plt.show()

â€¢This is a draft note.