In this HackerRank Cube Summation problem, we have to Define a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinates (1,1,1) and the last block is defined by the coordinates (n,n,n). Calculate the sum of the values of blocks whose x coordinate is between x1 and x2 (inclusive), y coordinate between y1 and y2 (inclusive), and z coordinate between z1 and z2 (inclusive).

HackerRank Cube Summation problem solution


Problem solution in Python programming.

T = int(input())
for i in range(T):
    N,M = [int(s) for s in input().split()]
    data = {}
    for j in range(M):
        info = input().split()
        if info[0] == "UPDATE":
            data[info[1]+" "+info[2]+" "+info[3]] = int(info[4])
        else:
            x1 = int(info[1])
            y1 = int(info[2])
            z1 = int(info[3])
            x2 = int(info[4])
            y2 = int(info[5])
            z2 = int(info[6])
            res = 0
            for k,v in data.items():
                corr = [int(s) for s in k.split()]
                if corr[0] <= x2 and x1 <= corr[0] and corr[1] <= y2 and y1 <= corr[1] and corr[2] <= z2 and z1 <= corr[2]:
                    res += v
            print(res)


Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {
    public static void update(int[][][]cube, int x,int y, int z, int W) {
        cube[x-1][y-1][z-1]=W;
    }
    public static long query(int[][][] cube, int x1, int y1, int z1, int x2, int y2, int z2) {
        long total = 0L;
        if (x1>x2) {
            int temp = x1;
            x1 = x2;
            x2 = temp;
        }
        if (y1>y2) {
            int temp = y1;
            y1 = y2;
            y2 = temp;
        }
        if (z1>z2) {
            int temp = z1;
            z1 = z2;
            z2 = temp;
        }
        for (int i = x1; i<=x2; i++) {
            for (int j = y1; j<=y2; j++) {
                for (int k = z1; k<=z2; k++) {
                    long temp = (long)cube[i-1][j-1][k-1];
                    total+=temp;
                }
            }
        }
        return total;
    }
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        int T = inp.nextInt();
        for (int i =0; i<T; i++) {
            int N = inp.nextInt();
            int M = inp.nextInt();
            int [][][] cube = new int [N][N][N];
            for (int j = 0; j<M; j++) {
                String op = inp.next();
                if (op.equals("UPDATE")) {
                    update(cube,inp.nextInt(),inp.nextInt(),inp.nextInt(),inp.nextInt());
                } else {
                    System.out.println(query(cube,inp.nextInt(),inp.nextInt(),inp.nextInt(),inp.nextInt(),inp.nextInt(),inp.nextInt()));
                }
            }
        }
    }
}


Problem solution in C++ programming.

#include <fstream>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int NMAX = 110;

int T, N, M, X1, Y1, Z1, X2, Y2, Z2, Val[NMAX][NMAX][NMAX];
long long Aib[NMAX][NMAX][NMAX];
char Type[20];

int LSB(int X)
{
    return (X & (X - 1)) ^ X;
}

void Update(int X, int Y, int Z, int Val)
{
    for(int i = Y; i <= N; i += LSB(i))
        for(int j = Z; j <= N; j += LSB(j))
            Aib[X][i][j] += Val;
}

long long Query(int X, int Y, int Z)
{
    long long Now = 0;
    for(int i = Y; i; i -= LSB(i))
        for(int j = Z; j; j -= LSB(j))
            Now += Aib[X][i][j];
    return Now;
}

long long Sum(int X1, int Y1, int Z1, int X2, int Y2, int Z2)
{
    long long Ans = 0;
    for(int i = X1; i <= X2; ++ i)
        Ans += (Query(i, Y2, Z2) - Query(i, Y1 - 1, Z2) - Query(i, Y2, Z1 - 1) + Query(i, Y1 - 1, Z1 - 1));
    return Ans;
}

int main()
{
    cin >> T;

    for(; T; T --)
    {
        for(int i = 1; i <= N; ++ i)
            for(int j = 1; j <= N; ++ j)
                for(int k = 1; k <= N; ++ k)
                    Aib[i][j][k] = Val[i][j][k] = 0;

        cin >> N >> M;
        for(int i = 1; i <= M; ++ i)
        {
            cin >> Type;
            if(Type[0] == 'U')
            {
                int W;
                cin >> X1 >> Y1 >> Z1 >> W;
                Update(X1, Y1, Z1, -Val[X1][Y1][Z1]);
                Update(X1, Y1, Z1, W);
                Val[X1][Y1][Z1] = W;
            }else
            {
                cin >> X1 >> Y1 >> Z1 >> X2 >> Y2 >> Z2;
                cout << Sum(X1, Y1, Z1, X2, Y2, Z2) << "\n";
            }
        }
    }
}


Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct s_elem
{
  int x;
  int y;
  int z;
  long long int value;
  struct s_elem *next;
} elem;

int place_value(elem *root, int x, int y, int z, long long int value)
{
  while (root != NULL)
    {
      if (root->x == x && root->y == y && root->z == z)
	{
	  root->value = value;
	  return 1;
	}
      root = root->next;
    }
  return 0;
}


void add_elem(elem **root, int x, int y, int z, long long int value)
{
  elem *newelem = (elem *) malloc(sizeof(elem));
  newelem->x = x;
  newelem->y = y;
  newelem->z = z;
  newelem->value = value;
  newelem->next = *root;
  *root = newelem;
}

long long int sum_list(elem *root, int x1, int y1, int z1, int x2, int y2, int z2)
{
  long long int sum = 0;
  while (root != NULL)
    {
      if (root->x >= x1 && root->x <= x2 && root->y >= y1 && root->y <= y2 && root->z >= z1 && root->z <= z2)
	sum += root->value;
      root = root->next;
    }
  return sum;
}

void free_list(elem **root)
{
  elem *tmp, *current = *root;
  while (current != NULL)
    {
      tmp = current->next;
      free(current);
      current = tmp;
    }
  *root = NULL;
}

int main()
{
  int test, i, j, size, query;
  int x, y, z, x1, y1, z1, x2, y2, z2;
  long long int value;
  elem *list = NULL;
  char *str = malloc(sizeof(char) * 10);
  scanf("%d", &test);
  for (i = 0; i < test; i++)
    {
      scanf("%d%d", &size, &query);
      for (j = 0; j < query; j++)
	{
	  scanf("%s", str);
	  if (str[0] == 'U')
	    {
	      scanf("%d%d%d%lld", &x, &y, &z, &value);
	      if (!place_value(list, x, y, z, value))
		{
		  add_elem(&list, x, y, z, value);
		}
	    }
	  else
	    {
	      scanf("%d%d%d%d%d%d", &x1, &y1, &z1, &x2, &y2, &z2);
	      printf("%lld\n", sum_list(list, x1, y1, z1, x2, y2, z2));
	    }
	}
      free_list(&list);
    }
  return 0;
}


Problem solution in JavaScript programming.

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'cubeSum' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts following parameters:
 *  1. INTEGER n
 *  2. STRING_ARRAY operations
 */

function cubeSum(n, operations) {
    // Write your code here
    // sparse matrix? + hash + bloomFilter
    let i = -1;
    const map = new Map();
    const queries = [];
    while (++i < operations.length) {
        const op = operations[i].split(' ');
        const name = op[0];
        switch (name) {
            case 'UPDATE':
                const [_u, x, y, z, w] = op.map(a => +a);
                const key = `${x}_${y}_${z}`;
                map.set(key, w);
                break;
            case 'QUERY':
                const [_q, x1, y1, z1, x2, y2, z2] = op.map(a => +a);
                let sum = 0
                for (const pair of map) {
                    const [key, value] = pair;
                    const [x,y,z] = key.split('_').map(a => +a);
                    
                    if (
                        x >= x1 && x <= x2 &&
                        y >= y1 && y <= y2 &&
                        z >= z1 && z <= z2
                    ) {
                        sum += value;
                    }
                }

                queries.push(sum);
                break;
            default:
                return;
        }
    }
    return queries;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const T = parseInt(readLine().trim(), 10);

    for (let TItr = 0; TItr < T; TItr++) {
        const firstMultipleInput = readLine().replace(/\s+$/g, '').split(' ');

        const matSize = parseInt(firstMultipleInput[0], 10);

        const m = parseInt(firstMultipleInput[1], 10);

        let ops = [];

        for (let i = 0; i < m; i++) {
            const opsItem = readLine();
            ops.push(opsItem);
        }

        const res = cubeSum(matSize, ops);

        ws.write(res.join('\n') + '\n');
    }

    ws.end();
}