Mueva los elementos de la array en la dirección dada y agregue elementos con el mismo valor

Dada una array m[ ][ ] de tamaño nxn que consta de números enteros y dado un carácter ‘x’ que indica la dirección. El valor de ‘x’ puede ser ‘u’, ‘d’, ‘l’, ‘r’ indicando Arriba, Abajo, Izquierda, Derecha correspondientemente. La tarea es mover el elemento en la dirección dada de modo que los elementos consecutivos que tengan el mismo valor se sumen en un solo valor y desplacen el resto del elemento. Además, cambie el elemento si el siguiente elemento en la dirección dada es 0. 

Por ejemplo: 
considere x = ‘l’ y la array m[][], 
32 3 3 
0 0 1 
10 10 8
Después de sumar 3 en la primera fila, 10 en la tercera fila y mover 1 en la segunda fila, 
Matrix se convertirá en 
32 6 0 
1 0 0 
20 8 0

Ejemplos:  

Input : x = 'l'
m[][] = { { 32, 3, 3, 3, 3 },
          { 0, 0, 1, 0, 0 },
          { 10, 10, 8, 1, 2},
          { 0, 0, 0, 0, 1},
          { 4, 5, 6, 7, 8 } }
Output :
32 6 6 0 0
1 0 0 0 0
20 8 1 2 0
1 0 0 0 0 0
4 5 6 7 8

Input : x = 'u'
m[][] = { { 10, 3, 32 },
        { 10, 0, 96 },
        { 5, 32, 96 } }
Output :
20 3 32
5 32 192
0 0 0

Enfoque: La idea es atravesar cada fila o columna (dependiendo de la dirección dada) desde el lado x de la fila o columna hacia x’ (opuesto a x). Por ejemplo, si el valor dado de x es ‘l’ (izquierda), comience a escanear cada fila de izquierda a derecha. Mientras se desplaza, almacene el elemento de fila o columna en la array 1-D temporal (por ejemplo, temp[]) omitiendo los elementos que tengan el valor 0 y la suma del elemento consecutivo si tienen el mismo valor. Después de eso, comience a copiar la array temporal temp[0..k] a la fila o columna actual desde el lado x (de la fila o columna) a x’ (opuesto a x) y complete el restablecimiento del elemento en 0.

Sea x = ‘l’, es decir, muévase hacia la izquierda. Por lo tanto, comience a copiar cada fila desde el índice más a la izquierda hasta el índice más a la derecha de la fila y almacene en una array temporal con el procesamiento de ignorar 0 y agregar dos elementos consecutivos en uno si tienen el mismo valor. A continuación se muestra la ilustración de la fila 1,  

Ahora, para cada uno, copie la array temporal a la fila actual desde el índice más a la izquierda hasta el índice más a la derecha. A continuación se muestra la ilustración de la fila 1,  

A continuación se muestra la implementación de este enfoque: 

C++

// C++ code to move matrix elements
// in given direction with add
// element with same value
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 50
 
// Function to shift the matrix
// in the given direction
void moveMatrix(char d[], int n,
                int a[MAX][MAX])
{
 
    // For right shift move.
    if (d[0] == 'r') {
 
        // for each row from
        // top to bottom
        for (int i = 0; i < n; i++) {
            vector<int> v, w;
            int j;
 
            // for each element of
            // row from right to left
            for (j = n - 1; j >= 0; j--) {
                // if not 0
                if (a[i][j])
                    v.push_back(a[i][j]);
            }
 
            // for each temporary array
            for (j = 0; j < v.size(); j++) {
                // if two element have same
                // value at consecutive position.
                if (j < v.size() - 1 && v[j] == v[j + 1]) {
                    // insert only one element
                    // as sum of two same element.
                    w.push_back(2 * v[j]);
                    j++;
                }
                else
                    w.push_back(v[j]);
            }
 
            // filling the each row element to 0.
            for (j = 0; j < n; j++)
                a[i][j] = 0;
 
            j = n - 1;
 
            // Copying the temporary
            // array to the current row.
            for (auto it = w.begin();
                 it != w.end(); it++)
                a[i][j--] = *it;
        }
    }
 
    // for left shift move
    else if (d[0] == 'l') {
 
        // for each row
        for (int i = 0; i < n; i++) {
            vector<int> v, w;
            int j;
 
            // for each element of the
            // row from left to right
            for (j = 0; j < n; j++) {
                // if not 0
                if (a[i][j])
                    v.push_back(a[i][j]);
            }
 
            // for each temporary array
            for (j = 0; j < v.size(); j++) {
                // if two element have same
                // value at consecutive position.
                if (j < v.size() - 1 && v[j] == v[j + 1]) {
                    // insert only one element
                    // as sum of two same element.
                    w.push_back(2 * v[j]);
                    j++;
                }
                else
                    w.push_back(v[j]);
            }
 
            // filling the each row element to 0.
            for (j = 0; j < n; j++)
                a[i][j] = 0;
 
            j = 0;
 
            for (auto it = w.begin();
                 it != w.end(); it++)
                a[i][j++] = *it;
        }
    }
 
    // for down shift move.
    else if (d[0] == 'd') {
        // for each column
        for (int i = 0; i < n; i++) {
            vector<int> v, w;
            int j;
 
            // for each element of
            // column from bottom to top
            for (j = n - 1; j >= 0; j--) {
                // if not 0
                if (a[j][i])
                    v.push_back(a[j][i]);
            }
 
            // for each temporary array
            for (j = 0; j < v.size(); j++) {
 
                // if two element have same
                // value at consecutive position.
                if (j < v.size() - 1 && v[j] == v[j + 1]) {
                    // insert only one element
                    // as sum of two same element.
                    w.push_back(2 * v[j]);
                    j++;
                }
                else
                    w.push_back(v[j]);
            }
 
            // filling the each column element to 0.
            for (j = 0; j < n; j++)
                a[j][i] = 0;
 
            j = n - 1;
 
            // Copying the temporary array
            // to the current column
            for (auto it = w.begin();
                 it != w.end(); it++)
                a[j--][i] = *it;
        }
    }
 
    // for up shift move
    else if (d[0] == 'u') {
        // for each column
        for (int i = 0; i < n; i++) {
            vector<int> v, w;
            int j;
 
            // for each element of column
            // from top to bottom
            for (j = 0; j < n; j++) {
                // if not 0
                if (a[j][i])
                    v.push_back(a[j][i]);
            }
 
            // for each temporary array
            for (j = 0; j < v.size(); j++) {
                // if two element have same
                // value at consecutive position.
                if (j < v.size() - 1 && v[j] == v[j + 1]) {
                    // insert only one element
                    // as sum of two same element.
                    w.push_back(2 * v[j]);
                    j++;
                }
                else
                    w.push_back(v[j]);
            }
 
            // filling the each column element to 0.
            for (j = 0; j < n; j++)
                a[j][i] = 0;
 
            j = 0;
 
            // Copying the temporary array
            // to the current column
            for (auto it = w.begin();
                 it != w.end(); it++)
                a[j++][i] = *it;
        }
    }
}
 
// Driven Program
int main()
{
    char d[2] = "l";
    int n = 5;
    int a[MAX][MAX] = { { 32, 3, 3, 3, 3 },
                        { 0, 0, 1, 0, 0 },
                        { 10, 10, 8, 1, 2 },
                        { 0, 0, 0, 0, 1 },
                        { 4, 5, 6, 7, 8 } };
 
    moveMatrix(d, n, a);
 
    // Printing the final array
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << a[i][j] << " ";
 
        cout << endl;
    }
 
    return 0;
}

Java

// Java code to move matrix
// elements in given direction
// with add element with same value
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to shift the matrix
    // in the given direction
    static void moveMatrix(char d,
                           int n,
                           int a[][])
    {
 
        // For right shift move.
        if (d == 'r') {
 
            // for each row from
            // top to bottom
            for (int i = 0; i < n; i++) {
                ArrayList<Integer> v = new ArrayList<Integer>();
                ArrayList<Integer> w = new ArrayList<Integer>();
                int j;
 
                // for each element of
                // row from right to left
                for (j = n - 1; j >= 0; j--) {
                    // if not 0
                    if (a[i][j] != 0)
                        v.add(a[i][j]);
                }
 
                // for each temporary array
                for (j = 0; j < v.size(); j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) {
                        // insert only one element
                        // as sum of two same element.
                        w.add(2 * v.get(j));
                        j++;
                    }
                    else
                        w.add(v.get(j));
                }
 
                // filling the each
                // row element to 0.
                for (j = 0; j < n; j++)
                    a[i][j] = 0;
 
                j = n - 1;
 
                // Copying the temporary
                // array to the current row.
                for (int it = 0; it < w.size(); it++)
                    a[i][j--] = w.get(it);
            }
        }
 
        // for left shift move
        else if (d == 'l') {
 
            // for each row
            for (int i = 0; i < n; i++) {
                ArrayList<Integer> v = new ArrayList<Integer>();
                ArrayList<Integer> w = new ArrayList<Integer>();
                int j;
 
                // for each element of the
                // row from left to right
                for (j = 0; j < n; j++) {
                    // if not 0
                    if (a[i][j] != 0)
                        v.add(a[i][j]);
                }
 
                // for each temporary array
                for (j = 0; j < v.size(); j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) {
                        // insert only one
                        // element as sum
                        // of two same element.
                        w.add(2 * v.get(j));
                        j++;
                    }
                    else
                        w.add(v.get(j));
                }
 
                // filling the each
                // row element to 0.
                for (j = 0; j < n; j++)
                    a[i][j] = 0;
 
                j = 0;
 
                for (int it = 0; it < w.size(); it++)
                    a[i][j++] = w.get(it);
            }
        }
 
        // for down shift move.
        else if (d == 'd') {
            // for each column
            for (int i = 0; i < n; i++) {
                ArrayList<Integer> v = new ArrayList<Integer>();
                ArrayList<Integer> w = new ArrayList<Integer>();
                int j;
 
                // for each element of
                // column from bottom to top
                for (j = n - 1; j >= 0; j--) {
                    // if not 0
                    if (a[j][i] != 0)
                        v.add(a[j][i]);
                }
 
                // for each temporary array
                for (j = 0; j < v.size(); j++) {
 
                    // if two element have
                    // same value at consecutive
                    // position.
                    if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) {
                        // insert only one element
                        // as sum of two same element.
                        w.add(2 * v.get(j));
                        j++;
                    }
                    else
                        w.add(v.get(j));
                }
 
                // filling the each
                // column element to 0.
                for (j = 0; j < n; j++)
                    a[j][i] = 0;
 
                j = n - 1;
 
                // Copying the temporary array
                // to the current column
                for (int it = 0; it < w.size(); it++)
                    a[j--][i] = w.get(it);
            }
        }
 
        // for up shift move
        else if (d == 'u') {
            // for each column
            for (int i = 0; i < n; i++) {
                ArrayList<Integer> v = new ArrayList<Integer>();
                ArrayList<Integer> w = new ArrayList<Integer>();
                int j;
 
                // for each element of column
                // from top to bottom
                for (j = 0; j < n; j++) {
                    // if not 0
                    if (a[j][i] != 0)
                        v.add(a[j][i]);
                }
 
                // for each temporary array
                for (j = 0; j < v.size(); j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) {
                        // insert only one element
                        // as sum of two same element.
                        w.add(2 * v.get(j));
                        j++;
                    }
                    else
                        w.add(v.get(j));
                }
 
                // filling the each
                // column element to 0.
                for (j = 0; j < n; j++)
                    a[j][i] = 0;
 
                j = 0;
 
                // Copying the temporary
                // array to the current
                // column
                for (int it = 0; it < w.size(); it++)
                    a[j++][i] = w.get(it);
            }
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        char d = 'l';
        int n = 5;
        int a[][] = { { 32, 3, 3, 3, 3 },
                      { 0, 0, 1, 0, 0 },
                      { 10, 10, 8, 1, 2 },
                      { 0, 0, 0, 0, 1 },
                      { 4, 5, 6, 7, 8 } };
 
        moveMatrix(d, n, a);
 
        // Printing the
        // final array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(a[i][j] + " ");
 
            System.out.println();
        }
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)

Python3

# Python3 code to move matrix elements
# in given direction with add
# element with same value
MAX = 50
 
# Function to shift the matrix
# in the given direction
def moveMatrix(d, n, a):
 
    # For right shift move.
    if (d[0] == 'r'):
 
        # For each row from
        # top to bottom
        for i in range(n):
            v = []
            w = []
 
            # For each element of
            # row from right to left
            for j in range(n - 1, -1, -1):
                 
                # if not 0
                if (a[i][j]):
                    v.append(a[i][j])
 
            # For each temporary array
            j = 0
            while (j < len(v)):
                 
                # If two element have same
                # value at consecutive position.
                if (j < len(v) - 1 and
                   v[j] == v[j + 1]):
                     
                    # Insert only one element
                    # as sum of two same element.
                    w.append(2 * v[j])
                    j += 1
                 
                else:
                    w.append(v[j])
                     
                j += 1
 
            # Filling the each row element to 0.
            for j in range(n):
                a[i][j] = 0
 
            j = n - 1
 
            # Copying the temporary
            # array to the current row.
            for it in w:
                a[i][j] = it
                j -= 1
 
    # For left shift move
    elif (d[0] == 'l'):
 
        # For each row
        for i in range(n):
            v = []
            w = []
 
            # For each element of the
            # row from left to right
            for j in range(n):
                 
                # If not 0
                if (a[i][j]):
                    v.append(a[i][j])
 
            # For each temporary array
            j = 0
            while(j < len(v)):
                 
                # If two element have same
                # value at consecutive position.
                if (j < len(v) - 1 and
                   v[j] == v[j + 1]):
                     
                    # Insert only one element
                    # as sum of two same element.
                    w.append(2 * v[j])
                    j += 1
                 
                else:
                    w.append(v[j])
                     
                j += 1
 
            # Filling the each row element to 0.
            for j in range(n):
                a[i][j] = 0
 
            j = 0
 
            for it in w:
                a[i][j] = it
                j += 1
 
    # For down shift move.
    elif (d[0] == 'd'):
         
        # For each column
        for i in range(n):
            v = []
            w = []
 
            # For each element of
            # column from bottom to top
            for j in range(n - 1, -1, -1):
                 
                # If not 0
                if (a[j][i]):
                    v.append(a[j][i])
 
            # For each temporary array
            j = 0
            while(j < len(v)):
 
                # If two element have same
                # value at consecutive position.
                if (j <len( v) - 1 and
                   v[j] == v[j + 1]):
                     
                    # Insert only one element
                    # as sum of two same element.
                    w.append(2 * v[j])
                    j += 1
                 
                else:
                    w.append(v[j])
                     
                j += 1
                     
            # Filling the each column element to 0.
            for j in range(n):
                a[j][i] = 0
 
            j = n - 1
 
            # Copying the temporary array
            # to the current column
            for it in w:
                a[j][i] = it
                j -= 1
                 
    # For up shift move
    elif (d[0] == 'u'):
         
        # For each column
        for i in range(n):
            v = []
            w = []
 
            # For each element of column
            # from top to bottom
            for j in range(n):
                 
                # If not 0
                if (a[j][i]):
                    v.append(a[j][i])
 
            # For each temporary array
            j = 0
            while(j < len(v)):
                 
                # If two element have same
                # value at consecutive position.
                if (j < len(v) - 1 and
                   v[j] == v[j + 1]):
                     
                    # Insert only one element
                    # as sum of two same element.
                    w.append(2 * v[j])
                    j += 1
                 
                else:
                    w.append(v[j])
                j += 1
 
            # Filling the each column element to 0.
            for j in range(n):
                a[j][i] = 0
 
            j = 0
 
            # Copying the temporary array
            # to the current column
            for it in w:
                a[j][i] = it
                j += 1
 
# Driver Code
if __name__ == "__main__":
 
    d = ["l"] * 2
    n = 5
    a = [ [ 32, 3, 3, 3, 3 ],
          [ 0, 0, 1, 0, 0 ],
          [ 10, 10, 8, 1, 2 ],
          [ 0, 0, 0, 0, 1 ],
          [ 4, 5, 6, 7, 8 ] ]
 
    moveMatrix(d, n, a)
 
    # Printing the final array
    for i in range(n):
        for j in range(n):
            print(a[i][j], end = " ")
 
        print()
 
# This code is contributed by chitranayal

C#

// C# code to move matrix elements
// in given direction with add
// element with same value
using System;
using System.Collections.Generic;
 
class GFG {
    // Function to shift the matrix
    // in the given direction
    static void moveMatrix(char d, int n,
                           int[, ] a)
    {
 
        // For right shift move.
        if (d == 'r') {
 
            // for each row from
            // top to bottom
            for (int i = 0; i < n; i++) {
                List<int> v = new List<int>();
                List<int> w = new List<int>();
                int j;
 
                // for each element of
                // row from right to left
                for (j = n - 1; j >= 0; j--) {
                    // if not 0
                    if (a[i, j] != 0)
                        v.Add(a[i, j]);
                }
 
                // for each temporary array
                for (j = 0; j < v.Count; j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.Count - 1 && v[j] == v[j + 1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.Add(2 * v[j]);
                        j++;
                    }
                    else
                        w.Add(v[j]);
                }
 
                // filling the each
                // row element to 0.
                for (j = 0; j < n; j++)
                    a[i, j] = 0;
 
                j = n - 1;
 
                // Copying the temporary
                // array to the current row.
                for (int it = 0; it < w.Count; it++)
                    a[i, j--] = w[it];
            }
        }
 
        // for left shift move
        else if (d == 'l') {
 
            // for each row
            for (int i = 0; i < n; i++) {
                List<int> v = new List<int>();
                List<int> w = new List<int>();
                int j;
 
                // for each element of the
                // row from left to right
                for (j = 0; j < n; j++) {
                    // if not 0
                    if (a[i, j] != 0)
                        v.Add(a[i, j]);
                }
 
                // for each temporary array
                for (j = 0; j < v.Count; j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.Count - 1 && v[j] == v[j + 1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.Add(2 * v[j]);
                        j++;
                    }
                    else
                        w.Add(v[j]);
                }
 
                // filling the each
                // row element to 0.
                for (j = 0; j < n; j++)
                    a[i, j] = 0;
 
                j = 0;
 
                for (int it = 0; it < w.Count; it++)
                    a[i, j++] = w[it];
            }
        }
 
        // for down shift move.
        else if (d == 'd') {
            // for each column
            for (int i = 0; i < n; i++) {
                List<int> v = new List<int>();
                List<int> w = new List<int>();
                int j;
 
                // for each element of
                // column from bottom to top
                for (j = n - 1; j >= 0; j--) {
                    // if not 0
                    if (a[j, i] != 0)
                        v.Add(a[j, i]);
                }
 
                // for each temporary array
                for (j = 0; j < v.Count; j++) {
 
                    // if two element have same
                    // value at consecutive position.
                    if (j < v.Count - 1 && v[j] == v[j + 1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.Add(2 * v[j]);
                        j++;
                    }
                    else
                        w.Add(v[j]);
                }
 
                // filling the each
                // column element to 0.
                for (j = 0; j < n; j++)
                    a[j, i] = 0;
 
                j = n - 1;
 
                // Copying the temporary array
                // to the current column
                for (int it = 0; it < w.Count; it++)
                    a[j--, i] = w[it];
            }
        }
 
        // for up shift move
        else if (d == 'u') {
            // for each column
            for (int i = 0; i < n; i++) {
                List<int> v = new List<int>();
                List<int> w = new List<int>();
                int j;
 
                // for each element of column
                // from top to bottom
                for (j = 0; j < n; j++) {
                    // if not 0
                    if (a[j, i] != 0)
                        v.Add(a[j, i]);
                }
 
                // for each temporary array
                for (j = 0; j < v.Count; j++) {
                    // if two element have same
                    // value at consecutive position.
                    if (j < v.Count - 1 && v[j] == v[j + 1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.Add(2 * v[j]);
                        j++;
                    }
                    else
                        w.Add(v[j]);
                }
 
                // filling the each
                // column element to 0.
                for (j = 0; j < n; j++)
                    a[j, i] = 0;
 
                j = 0;
 
                // Copying the temporary array
                // to the current column
 
                for (int it = 0; it < w.Count; it++)
                    a[j++, i] = w[it];
            }
        }
    }
 
    // Driven Code
    static void Main()
    {
        char d = 'l';
        int n = 5;
        int[, ] a = new int[, ] { { 32, 3, 3, 3, 3 },
                                  { 0, 0, 1, 0, 0 },
                                  { 10, 10, 8, 1, 2 },
                                  { 0, 0, 0, 0, 1 },
                                  { 4, 5, 6, 7, 8 } };
 
        moveMatrix(d, n, a);
 
        // Printing the final array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                Console.Write(a[i, j] + " ");
 
            Console.WriteLine();
        }
    }
}
// This code is contributed by
// Manish Shaw(manishshaw1)

PHP

<?php
// PHP code to move matrix
// elements in given
// direction with add element
// with same value
$MAX = 50;
 
// Function to shift the matrix
// in the given direction
function moveMatrix($d, $n, &$a)
{
    global $MAX;
     
    // For right shift move.
    if ($d[0] == 'r')
    {
         
        // for each row from
        // top to bottom
        for ($i = 0; $i < $n; $i++)
        {
            $v = array();
            $w = array();
            $j = 0;
 
            // for each element of
            // row from right to left
            for ($j = $n - 1; $j >= 0; $j--)
            {
                // if not 0
                if ($a[$i][$j])
                    array_push($v, $a[$i][$j]);
            }
 
            // for each temporary array
            for ($j = 0; $j < count($v); $j++)
            {
                // if two element have same
                // value at consecutive position.
                if ($j < count($v) - 1 &&
                    $v[$j] == $v[$j + 1])
                {
                    // insert only one element
                    // as sum of two same element.
                    array_push($w, 2 * $v[$j]);
                    $j++;
                }
                else
                    array_push($w, $v[$j]);
            }
 
            // filling the each
            // row element to 0.
            for ($j = 0; $j < $n; $j++)
                $a[$i][$j] = 0;
 
            $j = $n - 1;
 
            // Copying the temporary
            // array to the current row.
            for ($it = 0; $it != count($w); $it++)
                    $a[$i][$j--] = $w[$it];
        }
    }
 
    // for left shift move
    else if ($d[0] == 'l')
    {
        // for each row
        for ($i = 0; $i < $n; $i++)
        {
            $v = array(); $w = array();
            $j = 0;
 
            // for each element of the
            // row from left to right
            for ($j = 0; $j < $n; $j++)
            {
                // if not 0
                if ($a[$i][$j])
                    array_push($v,
                               $a[$i][$j]);
            }
 
            // for each temporary array
            for ($j = 0; $j < count($v); $j++)
            {
                // if two element have
                // same value at consecutive
                // position.
                if ($j < count($v) - 1 &&
                    $v[$j] == $v[$j + 1])
                {
                    // insert only one element
                    // as sum of two same element.
                    array_push($w, 2 * $v[$j]);
                    $j++;
                }
                else
                    array_push($w, $v[$j]);
            }
 
            // filling the each
            // row element to 0.
            for ($j = 0; $j < $n; $j++)
                $a[$i][$j] = 0;
 
            $j = 0;
 
            for ($it = 0; $it != count($w); $it++)
                    $a[$i][$j++] = $w[$it];
        }
    }
 
    // for down shift move.
    else if ($d[0] == 'd')
    {
        // for each column
        for ($i = 0; $i < $n; $i++)
        {
            $v = array(); $w = array();
            $j = 0;
 
            // for each element
            // of column from
            // bottom to top
            for ($j = $n - 1; $j >= 0; $j--)
            {
                // if not 0
                if ($a[$j][$i])
                    array_push($v, $a[$j][$i]);
            }
 
            // for each temporary array
            for ($j = 0; $j < count($v); $j++)
            {
                 
                // if two element have
                // same value at
                // consecutive position.
                if ($j < count($v) - 1 &&
                    $v[$j] == $v[$j + 1])
                {
                    // insert only one element
                    // as sum of two same element.
                    array_push($w, 2 * $v[$j]);
                    $j++;
                }
                else
                    array_push($w, $v[$j]);
            }
 
            // filling the each
            // column element to 0.
            for ($j = 0; $j < $n; $j++)
                $a[$j][$i] = 0;
 
            $j = $n - 1;
 
            // Copying the temporary array
            // to the current column
            for ($it = 0; $it != count($w); $it++)
                    $a[$j--][$i] = $w[$it];
        }
    }
 
    // for up shift move
    else if ($d[0] == 'u')
    {
        // for each column
        for ($i = 0; $i < $n; $i++)
        {
            $v = array(); $w = array();
            $j = 0;
 
            // for each element of column
            // from top to bottom
            for ($j = 0; $j < $n; $j++)
            {
                // if not 0
                if ($a[$j][$i])
                    array_push($v,
                               $a[$j][$i]);
            }
 
            // for each temporary array
            for ($j = 0; $j < count($v); $j++)
            {
                // if two element have same
                // value at consecutive position.
                if ($j < count($v) - 1 &&
                    $v[$j] == $v[$j + 1])
                {
                    // insert only one element
                    // as sum of two same element.
                    array_push($w, 2 * $v[$j]);
                    $j++;
                }
                else
                    array_push($w, $v[$j]);
            }
 
            // filling the each
            // column element to 0.
            for ($j = 0; $j < $n; $j++)
                $a[$j][$i] = 0;
 
            $j = 0;
 
            // Copying the temporary array
            // to the current column
            for ($it = 0; $it != count($w); $it++)
                    $a[$j++][$i] = $w[$it];
        }
    }
}
 
// Driven Code
$d = array("l");
$n = 5;
$a = array( array(32, 3, 3, 3, 3),
            array(0, 0, 1, 0, 0),
            array(10, 10, 8, 1, 2),
            array(0, 0, 0, 0, 1),
            array(4, 5, 6, 7, 8));
 
moveMatrix($d, $n, $a);
 
// Printing the final array
for ($i = 0; $i < $n; $i++)
{
    for ($j = 0; $j < $n; $j++)
        echo ($a[$i][$j]." ");
 
    echo ("\n");
}
 
// This code is contributed
// by Manish Shaw(manishshaw1)
?>

Javascript

<script>
// Javascript code to move matrix
// elements in given direction
// with add element with same value
     
    // Function to shift the matrix
    // in the given direction
    function moveMatrix(d,n,a)
    {
        // For right shift move.
        if (d == 'r') {
   
            // for each row from
            // top to bottom
            for (let i = 0; i < n; i++) {
                let v = [] ;
                let w = [] ;
                let j;
   
                // for each element of
                // row from right to left
                for (j = n - 1; j >= 0; j--) {
                    // if not 0
                    if (a[i][j] != 0)
                        v.push(a[i][j]);
                }
   
                // for each temporary array
                for (j = 0; j < v.length; j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.length - 1 && v[j] == v[j+1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.push(2 * v[j]);
                        j++;
                    }
                    else
                        w.push(v[j]);
                }
   
                // filling the each
                // row element to 0.
                for (j = 0; j < n; j++)
                    a[i][j] = 0;
   
                j = n - 1;
   
                // Copying the temporary
                // array to the current row.
                for (let it = 0; it < w.length; it++)
                    a[i][j--] = w[it];
            }
        }
   
        // for left shift move
        else if (d == 'l') {
   
            // for each row
            for (let i = 0; i < n; i++) {
                let v = [] ;
                let w = [] ;
                let j;
   
                // for each element of the
                // row from left to right
                for (j = 0; j < n; j++) {
                    // if not 0
                    if (a[i][j] != 0)
                        v.push(a[i][j]);
                }
   
                // for each temporary array
                for (j = 0; j < v.length; j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.length - 1 && v[j] == v[j+1]) {
                        // insert only one
                        // element as sum
                        // of two same element.
                        w.push(2 * v[j]);
                        j++;
                    }
                    else
                        w.push(v[j]);
                }
   
                // filling the each
                // row element to 0.
                for (j = 0; j < n; j++)
                    a[i][j] = 0;
   
                j = 0;
   
                for (let it = 0; it < w.length; it++)
                    a[i][j++] = w[it];
            }
        }
   
        // for down shift move.
        else if (d == 'd') {
            // for each column
            for (let i = 0; i < n; i++) {
                let v = [];
                let w = [];
                let j;
   
                // for each element of
                // column from bottom to top
                for (j = n - 1; j >= 0; j--) {
                    // if not 0
                    if (a[j][i] != 0)
                        v.push(a[j][i]);
                }
   
                // for each temporary array
                for (j = 0; j < v.length; j++) {
   
                    // if two element have
                    // same value at consecutive
                    // position.
                    if (j < v.length - 1 && v[j] == v[j+1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.push(2 * v[j]);
                        j++;
                    }
                    else
                        w.push(v[j]);
                }
   
                // filling the each
                // column element to 0.
                for (j = 0; j < n; j++)
                    a[j][i] = 0;
   
                j = n - 1;
   
                // Copying the temporary array
                // to the current column
                for (let it = 0; it < w.length; it++)
                    a[j--][i] = w[it];
            }
        }
   
        // for up shift move
        else if (d == 'u') {
            // for each column
            for (let i = 0; i < n; i++) {
                let v = [];
                let w = [];
                let j;
   
                // for each element of column
                // from top to bottom
                for (j = 0; j < n; j++) {
                    // if not 0
                    if (a[j][i] != 0)
                        v.push(a[j][i]);
                }
   
                // for each temporary array
                for (j = 0; j < v.length; j++) {
                    // if two element have
                    // same value at
                    // consecutive position.
                    if (j < v.length - 1 && v[j] == v[j+1]) {
                        // insert only one element
                        // as sum of two same element.
                        w.push(2 * v[j]);
                        j++;
                    }
                    else
                        w.push(v[j]);
                }
   
                // filling the each
                // column element to 0.
                for (j = 0; j < n; j++)
                    a[j][i] = 0;
   
                j = 0;
   
                // Copying the temporary
                // array to the current
                // column
                for (let it = 0; it < w.length; it++)
                    a[j++][i] = w[it];
            }
        }
    }
      
    // Driver Code
    let d = 'l';
    let n = 5;
     
    let a = [ [ 32, 3, 3, 3, 3 ],
          [ 0, 0, 1, 0, 0 ],
          [ 10, 10, 8, 1, 2 ],
          [ 0, 0, 0, 0, 1 ],
          [ 4, 5, 6, 7, 8 ] ]
     
    moveMatrix(d, n, a);
   
        // Printing the
        // final array
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++)
            document.write(a[i][j] + " ");
   
        document.write("<br>");
    }
     
    // This code is contributed by rag2127
</script>
Producción: 

32 6 6 0 0 
1 0 0 0 0 
20 8 1 2 0 
1 0 0 0 0 
4 5 6 7 8

 

Complejidad de Tiempo: O(n 2 )
Espacio Auxiliar: O(n)

Publicación traducida automáticamente

Artículo escrito por anuj0503 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *