Generating a cartesian product of multidimensional string array or dynamic lists [on hold]

I would like see an example or a sample VBA macro code which can generate a cartesian product of a multidimensional array with dynamic rows and columns. i.e. The number of rows and columns are not fixed.

All the below lists are part of multidimensional string array:

List 1:

Element 1: StackOverflow
Element 2: STACKOVERFLOW
Element 3: stackoverflow
Element n: .....

List 2:

Element 1: Private
Element 2: Pvt
Element 3: Pvt.
Element n: ....

List 3:

Element 1: Limited
Element 2: Ltd
Element 3: Ltd.
Element 4: ....

List n:

Element 1:....
Element 2:....
Element n:....

The number of lists and elements within each list are dynamic. The possible list it should generate is following output:

StackOverflow Private Limited
StackOverflow Private Ltd
StackOverflow Private Ltd.
StackOverflow Pvt Limited
StackOverflow Pvt Ltd
StackOverflow Pvt Ltd.
StackOverflow Pvt. Limited
StackOverflow Pvt. Ltd
StackOverflow Pvt. Ltd.
STACKOVERFLOW Private Limited
STACKOVERFLOW Private Ltd
STACKOVERFLOW Private Ltd.
STACKOVERFLOW Pvt Limited
STACKOVERFLOW Pvt Ltd
STACKOVERFLOW Pvt Ltd.
STACKOVERFLOW Pvt. Limited
STACKOVERFLOW Pvt. Ltd
STACKOVERFLOW Pvt. Ltd.
stackoverflow Private Limited
stackoverflow Private Ltd
stackoverflow Private Ltd.
stackoverflow Pvt Limited
stackoverflow Pvt Ltd
stackoverflow Pvt Ltd.
stackoverflow Pvt. Limited
stackoverflow Pvt. Ltd
stackoverflow Pvt. Ltd.

Would be great if someone can share a sample code. I have tried multiple codes, but they either use Microsoft Query or solves the problem of a fixed number of lists or sets.

Thank you in advance.

Why is my array declared as an array of references

Today, while compiling some code with GCC 4.9.2 for the first time, I encountered a strange error about an array being interpreted as an array of references.

I was able to reproduce the error with a quick example. Why is the constructor of Link interpreting buses as an array of references in the constructor of Stuff.

The following code works with MSVC10 and ICC 11.1

#include <iostream>

struct Bus
{
    Bus(std::string n) : name(n) {}
    std::string name;
};

template<typename T>
class Link
{
public:
    Link(const T* i)
    {
        data = (T*)i;   
    }

    const T* get() const
    {
        return data;
    }
private:
    T* data = nullptr;  
};

class Stuff
{
public:
    Stuff(Link<Bus> l_b) : link(l_b) {}
private:
    Link<Bus> link;
};

void print(Link<Bus> l)
{
    std::cout << l.get()->name << '\n';   
}

int main(void) {
    Bus buses[4] = { Bus("0"), Bus("1"), Bus("2"), Bus("3") };

    print(Link<Bus>(&buses[0]));

    Stuff s(Link<Bus>(&buses[0]));    

    return 0;
}

But with GCC and Clang, this gives an error :

main.cpp: In function 'int main()':

main.cpp:44:32: error: declaration of 'buses' as array of references

     Stuff s(Link<Bus>(&buses[0]));

Yet, the call to the print function works as intended. I am clueless about why the constructor fails.

I found a solution to that problem, by calling buses lik that in the call to the constructor of Stuff

Stuff s(Link<Bus>((&buses)[0]));    

But I’m really interested to know why it fails.

Live example here

C-style array vs std::array for library interface

I want to write a library with an interface that provide a read function.
C-style array is error prone but allow to pass a buffer of any size.
C++ array are safer but impose to be constructed with a size.

// interface.h

// C-style array
int read (std::uint8_t* buf, size_t len);

// C++ array
int read (std::array<std::uint8_t, 16>& buff)

How can I have the best of both worlds?

I was thinking about function template but it does not seems practical for a library interface.

template <size_t N>
int read (std::array<std::uint8_t, N>& buf);

EDIT
std::vector could be a good candidate but if we consider that char* and std::array do not have dynamic allocation.

EDIT I like a lot the solution with gsl::span. I am stuck with C++14 so no std::span. I don’t know if using a third library (gsl) will be an issue/allow.

EDIT I did not think that using char over another type could have some influence on the answer, so to be clearer it is to manipulate bytes. I change char to std::uint8_t

EDIT Since C++11 guarantee that a return std::vector will moved and not copied, returning std::vector<std::uint8_t> is acceptable.

std::vector<std::uint8_t> read();

Set array value to nothing in php

I try to set an array to nothing but it does not work (which is kind of expected).

$array = [
    'some_key' => my_function()

     /* 30 more rows of values */
];

function my_function() {
    return null;
}

print_r($array);

The above will display:

Array(
    'some_key' =>
)

The result I want is in this case an empty array item, because the function return a null value.

The alternative is a bit more ugly:

$some_key = my_function();

$array = [
     /* 30 more rows of values */
];

if(isset($some_key)) {
    $array['some_key] = $some_key;
}

function my_function() {
    return null;
}

print_r($array);

The reason I don’t like this approach is that I need to step away from my array tree and add the values in later.

It’s easier to see in a large array like this one:

This is my output but the input looks similar.

[component] => Array
    (
        [id] => my-snippet
        [raw] => my-snippet
        [view] => preview
        [template] => tool
        [type] => snippet
        [ctype] => text/html
        [url] => 
    )

To add functions or variables to this array tree looks great. Storing the array in a variable and then add the variables later is not as readale. Is it possible to solve?

C const pointer to const struct array as function argument

How can i make Alt.1 to work as intended by passing a pointer of an array and get the requested reference of an array in Alt.1 ?

struct mystruct
{
    int id1;
    int id2;
};

const struct mystruct local_struct[] = {
    {0, 55},
    {1, 66},
};

// Alt.1 i like to make this work (not working)
int get_reference_1(const struct mystruct *s){

   s = local_struct;
   return 0;
}

// Alt.2 works perfect but i like to use the return as status as in Alt.1.
const struct mystruct *get_reference_2(){
   return local_struct;
}

int main()
{
  struct mystruct *s = NULL;

  // Alt.1
  if(get_reference_1(s))
     /* Expected Fail*/
  else
     /* Expected Success*/

  // Alt.2
  s = get_reference_2()
  if(!s)
     /* Expected Fail*/
  else
     /* Expected Success*/

  return 0;
}

Maybe i’m thinking wrong and i need to pass a double pointer?

Edit: Corrected with ‘const’.
Edit2: Updated header.

Javascript – Use Variable as Array Index

Trying to use a variable as an array index. Variable addThirteen simply takes i and adds 13 to it. I need to use that result as the array index. Please see my code:

for (var i = 0; i < alphabetArr.length; i ++) {
  var addThirteen = (parseInt(i) + parseInt(13));
  var newCipher = new cipher(alphabetArr[i].letter, alphabetArr[addThirteen].letter);
}

This results in:

TypeError: undefined is not an object (evaluating
‘alphabetArr[addThirteen].letter’)

Appreciate any help.

Find data without repetitions multiple documents in MongoDB

Good morning, I am learning MongoDB but when trying to make a query I do not achieve the desired results.

The structure of the documents used is as follows:

use empresa

db.departamento_dos.insert (
{
 "Codigo": 2,
 "Nombre": "Contabilidad",
 "Presupuesto": 10000,
 "Empleados": 
 {
  "Empleado": { "DNI": "10340", "Nombre": "Andres", "Apellido": "Lopez"},
  "Empleado": { "DNI": "10341", "Nombre": "Paula", "Apellido": "Tovar"},
  "Empleado": { "DNI": "10342", "Nombre": "Andres", "Apellido": "Perez"},
  "Empleado": { "DNI": "10343", "Nombre": "Camila", "Apellido": "Perez"},
  "Empleado": { "DNI": "10344", "Nombre": "Cristian", "Apellido": "Forero"}
 }
}
)

and

db.departamento_tres.insert (
{
 "Codigo": 77,
 "Nombre": "Marketing",
 "Presupuesto": 30000,
 "Empleados": 
 {
  "Empleado uno": { "DNI": "10350", "Nombre": "Maria", "Apellido": "Perez"},
  "Empleado dos": { "DNI": "10351", "Nombre": "Angie", "Apellido": "Gómez"},
  "Empleado tres": { "DNI": "10352", "Nombre": "Andrea", "Apellido": "Lopez"},
  "Empleado cuatro": { "DNI": "10353", "Nombre": "Cristina", "Apellido": "Riaño"},
  "Empleado cinco": { "DNI": "10354", "Nombre": "Annie", "Apellido": "Castellanos"}
 }
}
)

My question is: how can I make a query by “Apellido” by eliminating repeated “Apellidos”?

I tried to use the different operator with a regular expression to auto-complete the query, but not work.

db.departamento_uno.distinct( "Empleados.Empleado", { /.*".Apellido"} )

and it always shows me an empty vector.

The idea is to be able to consult the two documents simultaneously. For example, the result I’m looking for would be:

[ "Lopez", "Tovar", "Perez", "Forero", "Gómez", "Riaño", "Castellanos"]

since the idea is to show each surname only once no matter how many times it appears

Any idea how you can make this query?

Thanks for the help.

Avoid PHP notice when destructuring array

Let’s say we have the following array:

$ourArray = [
   'a' => 'a',
   'b' => 'b',
];

And we try to get the value of key 'c' (which does not exist):

$someValue = $ourArray['c'] ?? null;

So, the previous statement will not throw any notice since it is just syntactic sugar to isset. To more information please visit PHP site.

In PHP7.1 was introduced symmetric array destructuring, so the idea is to destructure the array avoiding notices, so for example:

[
    'c' => $someValue
] = $ourArray;

So this will throw Undefined index: c in $ourArray ....

So, is there any way to avoid PHP to throw a notice using symmetric array destructuring? And without using functions like error_reporting or ini_set.

Is there a special behavior of parse_ini_file() I should be aware of? [on hold]

I have a quite big INI file (around 100kb and over 2000 lines) which I am trying to parse with PHP: $ini_array = parse_ini_file("config.ini");

But the function throw a warning: PHP Warning: syntax error, unexpected '(' in config.ini on line 1334 in ...

Looking at line 1334 won’t show any syntax error. Then I read this answer :

Short answer:

Don’t trust the line numbers, look for a syntax error in the lines before the line mentioned in the error.

I am confident that there is no error in the file because its used in production by an other tool wrote in Pascal.

So,

  • How I could check the file manually for errors ?

  • And if no syntax error exist in the file, is there a behavior of parse_ini_file() I should be aware of ?

g++ : array bound is not an integer constant before ‘]’ token

I’m having trouble with g++ producing this error code when I try to compile my code:

maze.h:16:29: error: array bound is not an integer constant before ‘]’ token<br /> bool canMove(int m[mazeSize][mazeSize], int r, int c);

Now, I have already done some research into this error and it seems to be causes by the array size not being known at compile time. I have tried making the array constant, but that ends up causing more errors later on as the array is reassigned later on in the code and produces this error:

maze.cpp: In member function ‘int Maze::startMazeGen()’:<br /> maze.cpp:185:15: error: assignment of read-only location ‘maze[i][j]’<br /> maze[i][j] = 1;<br /> ^

I have also seen people mention that it would just be easier to work with vectors instead, but I’m also having issues with trying to repurpose the code to work with vectors instead of arrays.

Here’s the rest of my code:

movement.h

#pragma once
#include <iostream>
#include <curses.h>
#ifndef MOVEMENT_H
#define MOVEMENT_H
class Movement
{
    public:
        static const int playerX = 2; // sets player starting position
        static const int playerY = 2;
};
#endif

movement.cpp

#include <iostream>
#include <curses.h>
#include <ctime>
#include "maze.h"
//#include "movement.h"

bool running = true;
int playerX = 2;
int playerY = 2;


//Maze::maze Maze::mazeGen;
//int Maze::mazeGen.Maze::maze::generateMaze::maze(int m[Maze::mazeSize]
[Maze::mazeSize], int r, int c);

// Detect Char input
// and move player in direction
void getUserInput()
{
    char userInput = getch();
    if (userInput == 'w') {
        int playerY2 = playerY - 1;
        if (Maze::maze[playerY2][playerX] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerY--;
            Maze::maze[playerY][playerX] = 'x';
    }
}
    if (userInput == 'a') {
        int playerX2 = playerX - 1;
        if (Maze::maze[playerY][playerX2] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerX--;
            Maze::maze[playerY][playerX] = 'x';
    }
}
    if (userInput == 's') {
        int playerY2 = playerY + 1;
        if (Maze::maze[playerY2][playerX] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerY++;
            Maze::maze[playerY][playerX] = 'x';
    }
}
    if (userInput == 'd') {
        int playerX2 = playerX + 1;
        if (Maze::maze[playerY][playerX2] == ' ') {
            Maze::maze[playerY][playerX] = ' ';
            playerX++;
            Maze::maze[playerY][playerX] = 'x';
        }
    }
}

// Main game update
// Runs through all functions required
void update()
{
    getUserInput();
    clear();
    Maze::generateMaze;
    refresh();
}


//
//
/*int main()
{
    // Initate nCurses display
    initscr();
    while (true) {
    update();
}
// End nCurses display
endwin();
return 0;
}*/

maze.h

#pragma once
// MAZE.h
#include <iostream>
#include <ctime>
#ifndef MAZE_H
#define MAZE_H
extern int r;
extern int c;
extern int mazeSize; //number can be changed to make some big sweaty mazes making it an even number makes it act a bit weird sometimes so its better to use an odd number
extern int maze[mazeSize][mazeSize];
class Maze
{
    public:
        int blockedSquare = 1;
        void move(int m[mazeSize][mazeSize], int &r, int &c);
        bool canMove(int m[mazeSize][mazeSize], int r, int c);
        void solve(int m[mazeSize][mazeSize], int &r, int &c);
        bool canSolve(int m[mazeSize][mazeSize], int r, int c);
        void generateMaze(int m[mazeSize][mazeSize], int r, int c);
        int findStart();
        void printMaze(int m[mazeSize][mazeSize]);
        int startMazeGen();
};
#endif

maze.cpp

#include <iostream>
#include <ctime>
#include <vector>
#include "maze.h"
bool foundExit = false;
int mazeSize = 31;
int maze[mazeSize][mazeSize] = { 0 };
void Maze::generateMaze(int const m[mazeSize][mazeSize], int r, int c)
{

    bool made = false;

    while (made == false)
    {
        if (c == mazeSize - 1)
            foundExit = true;


        if (canSolve(m, r, c))
        {
            solve(m, r, c);
        }
        else if (canMove(m, r, c))
        {
            m[r][c] = 2; //2 means you can't move from that square, setting any lower stops maze from being made
            move(m, r, c); //move to first open space that can be found
        }
        else
            made = true;

    }

}


void Maze::move(int m[mazeSize][mazeSize], int &r, int &c)
{
    if (m[r][c + 1] == 0)
        c++;
    else if (m[r + 1][c] == 0)
        r++;
    else if (m[r][c - 1] == 0)
        c--;
    else if (m[r - 1][c] == 0)
        r--;
    else
        generateMaze(maze, r, c); //if maze cant be solved it generates a new one so the player doesnt have something that is impossible to solve

}

bool Maze::canMove(int m[mazeSize][mazeSize], int r, int c) //if there is an adjacent zero space, return true
{
    if (m[r][c + 1] == 0)
        return true;
    else if (m[r + 1][c] == 0)
        return true;
    else if (m[r][c - 1] == 0)
        return true;
    else if (m[r - 1][c] == 0)
        return true;
    else
        return false;
}

void Maze::solve(int m[mazeSize][mazeSize], int &r, int &c) //solves maze through with dijkstras algorithmto ensure it can be solved
{
    bool foundSolution = false;

    while (foundSolution == false)
    {

        int direction = (1 + rand() % 4) * 3;

        switch (direction)
        {
        case 3:
            if (c + 1 <= mazeSize - 1 && m[r][c + 2] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r][c + 1] == blockedSquare)
            {
                if (c == mazeSize - 2 && foundExit == true)
                    ; //do nothing
                else
                {
                    c++;
                    foundSolution = true;
                }
            }
            break;
        case 6:
            if (r + 1 <= mazeSize - 2 && m[r + 2][c] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r + 1][c] == blockedSquare && c != 0 && c != mazeSize - 1)
            {
                r++;
                foundSolution = true;
            }
            break;
        case 9:
            if (c - 1 >= 0 && m[r][c - 2] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r][c - 1] == blockedSquare && c - 1 != 0)
            {
                c--;
                foundSolution = true;
            }
            break;
        case 12:
            if (r - 1 >= 1 && m[r - 2][c] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r - 1][c] == blockedSquare && c != 0 && c != mazeSize - 1)
            {
                r--;
                foundSolution = true;
            }
            break;
        }
    }

    m[r][c] = 0;
}



bool Maze::canSolve(int m[mazeSize][mazeSize], int r, int c) //if an adjacent square can be moved to, return true
{
    bool solvable = false;

    if (r <= mazeSize - 3 && m[r + 2][c] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r + 1][c] == blockedSquare && c != 0 && c != mazeSize - 1) //if adjacent space can be moved to 
    {
        solvable = true;
    }
    else if (c <= mazeSize - 2 && m[r][c + 2] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r][c + 1] == blockedSquare)
    {
        if (c == mazeSize - 2 && foundExit == true)
            ; //do nothing
        else
        {
            solvable = true;
        }
    }
    else if (r >= 2 && m[r - 2][c] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r - 1][c] == blockedSquare && c != 0 && c != mazeSize - 1) //if not on extreme left or right
    {
        solvable = true;
    }
    else if (c >= 1 && m[r][c - 2] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r][c - 1] == blockedSquare && c - 1 != 0)
    {
        solvable = true;
    }

    return solvable;
}

int Maze::findStart()
{
    return 1 + rand() % (mazeSize - 2);
}

void Maze::printMaze(int m[mazeSize][mazeSize])
{

    std::cout << std::endl;

    for (int i = 0; i < mazeSize; ++i) {
        for (int j = 0; j < mazeSize; ++j)
        {
            switch (m[i][j])
            {
            case 0:
                std::cout << "  ";
                break;
            case 1:
                std::cout << "??";
                break;
            case 2:
                std::cout << "  ";
                break;
            case 3:
                std::cout << "  ";
                break;
            }
        }
        std::cout << std::endl;
    }
}

int Maze::startMazeGen()
{
    srand(time(0));

    for (int i = 0; i < mazeSize; ++i)
        for (int j = 0; j < mazeSize; ++j)
            maze[i][j] = 1;

    int r = findStart();
    //int r = 0;
    int c = 0;

    maze[r][c] = 0;

    generateMaze(maze, r, c);
    maze[r][c] = 2;
    printMaze(maze);
    std::cout << "Press enter to continue ...";
    std::cin.get();
}

The purpose of this code is to randomly generate a maze, solve it, and then print it to the screen if it can be solved. If the maze can’t be solved, it keeps generating a new one until it can be solved.I aim to make this work with the movement code so that the user can navigate the maze.

Any help is appreciated on this issue. Thank you!