DEV Community

dinhanhx
dinhanhx

Posted on

1 1

Understand n dimension array with real life examples

Scenario

You are/were struggling with one of these terms: nested array, high dimension, n dimension array, ... Probably you have tried to visualize an n dimension array and got stuck at 3 dimension or even 2.

The simple way to understand

You don't need to visualize it. You just need to know that an n dimension array is a group of groups ... (many "of groups").

Let start with 1D array. 1D array is a group of values [1, 2, 3]. 2D array is a group of 1D groups [[1, 2, 3], [1, 2, 3]]. 3D array is a group of 2D groups [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]].

An n dimension array is also just a 1D array whose values are organized into groups. This is 1D array [1, 2, 3, 4, 5, 6]. Now we will group 123, and 456. By doing that, it becomes 2D array [[1, 2, 3], [4, 5, 6]]. Now we put each value into a group. As a result, 3D array is made [[[1], [2], [3]], [[4], [5], [6]]].

Every array has a very important attribute called shape. A shape is a set of the number of groups/values in each dimension (ordered from the highest dimension to the lowest one). Let visit the previous example. 1D array has 6 values or shape (6). 2D array has 2 groups, each group has 3 values. In other word, its shape is (2, 3). That 3D array has shape (2, 3, 1).

Real life example 1: A book

A book is a 5D array of letters whose shape is (c, p, s, w, l). A book has C chapters. Each chapter has P paragraphs. Each paragraph has S sentences. Each sentence has W words. Each word has L letters.

Real life example 2: A library

A library is a 7D array of letters. A library has G genres. Each genre has B books. And so on.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay