Verifying the legitimacy of the elements in an n-dimensional array

In my journey to create my own Tensor class (n-dimensional arrays) in typescript, I have devised a structure where the data is stored in a 1D array property, and the shape of the data is stored separately for indexing purposes.

My goal is to develop a function similar to numpy.array, which takes in multi-dimensional array data, flattens it into a 1D array, and then extracts the shape.

However, it is crucial for this function to validate if the input array has a consistent shape throughout (often referred to as having a "homogeneous shape").

Example 1

For instance, giving the following input to the function:

data = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]],
]

the expected output would be a tensor with the shape (2, 2, 2) and a flat array of elements [1, 2, 3, ..., 8] representing the data inside the tensor.

Example 2

Conversely, if the input is:

data = [
  [[1], [3, 4]],
  [[5, 6], [7, 8]],
]

the function should fail to validate the input due to the inconsistent shape with a sub-array containing only the element 1.

Example 3

Similarly, when provided with:

data = [
  [[1], 2],
  [3, 4],
]

the function should fail for the same reason, as the sub-array containing 1 is inconsistent with the rest of the data.

While numpy.array is capable of detecting such inconsistencies and raising errors, I am in search of an algorithm or method to achieve the same. Any guidance or assistance in this experimental project would be greatly appreciated.

Note: While I understand that utilizing an existing library for this task would be more efficient, my current endeavor is purely for educational purposes. As I lack extensive knowledge about tensors, any suggestions on where to start or what to learn beforehand would be highly valued.

Answer №1

This may not be the most efficient solution, but it is functional for an experimental project. The output includes an additional '0' for the dimensions, which represents the inner dimension. You can either remove the first element of the array or handle this case differently. In my opinion, it is reasonable to consider a number as an array with zero dimensions.

/// This code snippet checks if two arrays are equal
function arraysEqual(a: any[], b: any[]) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length !== b.length) return false;

  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

function testArray(x: any): [number[], number[]] {
  if (Array.isArray(x)) {
    let lastDim: number[] | undefined = undefined;
    let numbers: number[] = [];
    if (x.length === 0) {
      throw "Empty array";
    }
    for (const el of x) {
      const [d, n] = testArray(el);
      if (lastDim === undefined) {
        lastDim = d;
      }

      if (!arraysEqual(lastDim, d)) {
        throw "Dimensions not equal";
      }
      numbers.push(...n);
    }
    if (lastDim === undefined) {
      throw "Should never happen, but this line makes typescript happy :)";
    }
    lastDim.push(x.length);
    return [lastDim, numbers];
  } else if (typeof x === "number") {
    return [[0], [x]];
  } else {
    throw "Not an array or a number";
  }
}

const data1 = [
  [
    [1, 2],
    [3, 4],
  ],
  [
    [5, 6],
    [7, 8],
  ],
];

console.log(testArray(data1));

const data2 = [
  [[1], [3, 4]],
  [
    [5, 6],
    [7, 8],
  ],
];

try {
  console.log(testArray(data2));
} catch (e) {
  console.error(e);
}

const data3 = [
  [[1], 2],
  [3, 4],
];

try {
  console.log(testArray(data3));
} catch (e) {
  console.error(e);
}

[LOG]: [[0, 2, 2, 2], [1, 2, 3, 4, 5, 6, 7, 8]] 
[ERR]: "Dimensions not equal" 
[ERR]: "Dimensions not equal" 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some best practices for integrating ES2020 into an Angular project?

Below is the content of my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap&q ...

Converting a JSON array into a single JSON object using Powershell

I need assistance converting a JSON array into a single JSON Object. I have provided the output screenshot for reference: https://i.sstatic.net/vT55z.png My desired output is shown in this screenshot: https://i.sstatic.net/rL8Yp.png This is the PowerShel ...

Ways to transform a nested list to mimic the behavior of a numpy array

I have been working on implementing an algorithm in Python to count subsets with a given sum. Here is the code snippet: import numpy as np maxN = 20 maxSum = 1000 minSum = 1000 base = 1000 dp = np.zeros((maxN, maxSum + minSum)) v = np.zeros((maxN, maxS ...

What is the process for establishing the default type for an Activity Entity in Microsoft Dynamics?

Currently in the process of restructuring a portion of script code associated with the Fax Activity Entity within Microsoft Dynamics. Within the script code, the following can be found: document.getElementById("regardingobjectid").setAttribute("defaulttyp ...

Unable to execute functions on observable outcomes

Let's discuss an interface called Vehicle, a class named Car that implements it, and a method within the class titled isColorRed: export interface Vehicle{ color : string; } export class Car implements Vehicle{ color : string; constructo ...

Encountered an error during npm installation: Fetch Package Metadata error occurred while attempting to request from http://registry.npmjs.org/concurrently, the cause being a socket hangup

I am encountering the following errors: "An unexpected fetchPackageMetaData error occurred while making a request to http://registry.npmjs.org/concurrently failed due to a socket hang up." I am currently connected through a corporate proxy with the firew ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

Performing unit tests in Angular 2 with karma

Trying to grasp the concept of unit testing in Angular has been quite a challenge for me, especially since I am still navigating through Angular 2 and its syntax. Understanding testing becomes even more intricate. I attempt to follow the examples provided ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

How do I retrieve the data returned from the component.ts file in Angular Material's MatTableModule when it is not directly inside the mat-table in the template?

I'm currently working on an Angular 5 project where I have integrated a table to display data using MatTableModule from angular material. This specific inquiry consists of two parts. Within my project, there is a service that sends a GET request to t ...

What sets PHP array apart from PHP Constant?

Out of curiosity, I'm wondering if there is any performance benefit, such as reduced memory usage or resource utilization, when storing 50 different setting variables in PHP in the following ways: 1. Saved into an array like this $config['faceb ...

Transforming retrieved data into an array using Node.js

Got some data from a URL that looks like this: data=%5B1%2C2%2C3%2C4%2C0%5D which when decoded is [1,2,3,4,0]. Used the snippet below to parse the data: var queryObj = querystring.parse( theUrl.query ); Seems like it's not an array. How can I con ...

What methods can I use to prevent a JavaScript array from getting filled during page loading?

Looking for assistance to populate an array using JQuery with option values from multiple select elements. I need the array to reset and fill with new options each time a select element is used. Strangely, despite my efforts, the array appears pre-filled w ...

Formatting HTML Output Using PHP

Looking to format html output sourced from a database using php and facing an issue: Desired Format: ... <li> <div class="row-wrapper"> <div class="some-class-1">ARRAY-ELEMENT-1</div> <div class="some-class-1" ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Guide on linking enum values with types in TypeScript

My enum type is structured as follows: export enum API_TYPE { INDEX = "index_api", CREATE = "create_api", SHOW = "show_api", UPDATE = "update_api", DELETE = "destroy_api" }; Presently, I have a f ...

JavaScript rearrange array elements

Currently, I'm attempting to move the values of an array over by a random amount. For instance: var array = [1,2,3,4]; var shiftAmount = 1; The goal is to shift the array so that it looks like [4,1,2,3] ...

Utilize Angular's ng-repeat directive to iterate through this JSON data structure for implementing user-to

Struggling with the user-to-user messaging interface on an app and having difficulty using ng-repeat on the items. Here is the provided data: { "ID": 4118, "CreatedDate": "2015-08-20T03:12:50.397", "recipient": [ { ...

Tabulating Non-Prime Numbers

I am working on developing a method that will be able to determine and return the quantity of non-prime numbers present in an integer array. The existing method for marking prime numbers within an array is as follows (this portion does not require any mod ...

Using Typescript: Utilizing generic types within the parent class

I'm currently facing an issue with the code snippet below, which is a simplified example: class QueryArgs { studentId?: string; teacherId?: string; } class BaseValidator<T> { protected args: T; constructor(args: T) { this.args = a ...