Tag Archives: data structure

[Solved] Nacos1.3.2 Startup Error: Unable to start embedded Tomcat

Recently, I started to plan to learn springcloud-alibaba, so I downloaded the Nacos installation package on the GitHub official website, and found an error on startup.

Error message: Unable to start embedded Tomcat
the built-in Tomcat cannot be loaded.

Opened the conf folder and saw a nacos-mysql.sql
It seems to import a database script, so I created a database named nacos in the local database
and executed this sql script, which generated some tables.

With a database and tables, we must change the configuration.
So I opened application.properties with an editor
I saw that there is a place to configure the db, so I changed it.

After saving
enter the bin directory again and double-click startbat.cmd to start.

I found that I still reported an error.


Caused by: java.net.UnknownHostException: jmenv.tbsite.net

Here I have changed the configuration file again, but it has no effect.

The key point is that during startup, I noticed a message,
Nacos has been started in cluster mode. Cluster list is []

I wonder if this is the problem, because I clicked run and did not configure the Nacos cluster.

So I use the editor to open the startup.cmd in the dictory bin
see a key message

Here you can configure click mode startup, so try to change the startup configuration to click mode startup

Exit after saving. Double click the startup file startup.cmd

It started normally this time.

Enter in Browser: localhost:8848/nacos/index.html

Normally access the Nacos configuration center.

[Solved] G2o pointer error: error: no matching function for call to ‘g2o::BlockSolver

G2o pointer error

1. Problem description I

error: no matching function for call to ‘g2o::BlockSolver<g2o::BlockSolverTraits<-1, -1> >::BlockSolver(SlamLinearSolver*&)

And prompt

std::unique_ptr

The reason for the pointer may be a repeated reference.

G2oSolver::G2oSolver()
{
  // Step 1: Create a linear solver LinearSolver
  SlamLinearSolver *linearSolver = new SlamLinearSolver();
  linearSolver->setBlockOrdering(false);
  // Step 2: Create the BlockSolver and initialize it with the linear solver defined above
  SlamBlockSolver *blockSolver = new SlamBlockSolver(linearSolver);
  // Step 3: Create the total solver solver and select one from GN, LM, DogLeg and initialize it with the block solver BlockSolver defined above
  g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(blockSolver);
  // Step 4: Create the sparse optimizer (SparseOptimizer)
  mOptimizer.setAlgorithm(solver);
}

Modified code:

G2oSolver::G2oSolver()
{
  // Step 1: Create a linear solver LinearSolver
  SlamLinearSolver *linearSolver = new SlamLinearSolver();
  linearSolver->setBlockOrdering(false);
  // Step 2: Create the BlockSolver and initialize it with the linear solver defined above
  SlamBlockSolver *blockSolver=new SlamBlockSolver(std::unique_ptr<SlamLinearSolver>(linearSolver));
  // Step 3: Create the total solver solver and select one from GN, LM, DogLeg and initialize it with the above block solver BlockSolver
  g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(std::unique_ptr<SlamBlockSolver>( blockSolver));
  // Step 4: Create the Sparse Optimizer (SparseOptimizer)
  mOptimizer.setAlgorithm(solver);
}

2. Problem description II

fatal error: cs.h: No such file or directory

the error is in /usr/local/include/g2o/solvers/csparse/csparse_extension.h:

#include <cs.h>

Install
CSparse

sudo apt-get install libsuitesparse-dev

Find the header file

/usr/include/suitesparse/cs.h

add the header files in CMakeLists.txt:

include_directories("/usr/include/suitesparse") 
target_link_libraries(${PROJECT_NAME}_karto_slam_node
  ${catkin_LIBRARIES}
  ${Boost_LIBRARIES}
  sba
  ${CERES_LIBRARIES}
  gtsam

  ${G2O_LIBRARIES}
  ${SUITESPARSE_LIBRARIES}
)

[Solved] fatal error: cuda_runtime.h: No such file or directory

Background

Today, I want to run a yolact model, but in the process of training, I need a DCN network model. This requires CUDA to compile relevant files, but an error is reported. The main errors are:

	cuda_runtime.h: No such file or directory

I spent an afternoon reading a lot of blogs, but I didn’t solve it. Later I knew why. In fact, the solution is also very simple, that is, add some folder paths of CUDA installation directory to environment variables. The following are the solutions for the windows operating system:

Add the following two paths to the environment variable path:

	C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.0\bin
	C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.0\lib\x64

Basically, everyone’s default installation path is this. You only need to replace v11.0 according to their installed CUDA version number.

[Solved] ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregate

The MySQL table structure is as follows:

mysql> select * from fruits ;
+------+------+------------+---------+
| f_id | s_id | f_name     | f_price |
+------+------+------------+---------+
| a1   |  101 | apple      |    5.20 |
| a2   |  103 | apricot    |    2.20 |
| b1   |  101 | blackberry |   10.20 |
| b2   |  104 | berry      |    7.60 |
| b5   |  107 | xxxx       |    3.60 |
| bs1  |  102 | orange     |   11.20 |
| bs2  |  105 | melon      |    8.20 |
| c0   |  101 | cherry     |    3.20 |
| l2   |  104 | lemon      |    6.40 |
| m1   |  106 | mango      |   15.70 |
| m2   |  105 | xbabay     |    2.60 |
| m3   |  105 | xxtt       |   11.60 |
| o2   |  103 | coconut    |    9.20 |
| t1   |  102 | banana     |   10.30 |
| t2   |  102 | grape      |    5.30 |
| t4   |  107 | xbababa    |    3.60 |
+------+------+------------+---------+

According to s_ ID groups the table data, and the error message is as follows

mysql> select * from fruits group by s_id;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
 'exercise.fruits.f_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible 
 with sql_mode=only_full_group_by

Query SQL_Mode mode

mysql> select @@session.sql_mode;
+-------------------------------------------------------------------------------------------------------------------------------------------+
| @@session.sql_mode                                                                                                                        |
+-------------------------------------------------------------------------------------------------------------------------------------------+
| ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,
ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+-------------------------------------------------------------------------------------------------------------------------------------------+

Reason: only is added after MySQL 5.7_full_group_By roughly means that the column you select must be included in group by (for example, select a, B from table, group by a, B;), or you are an aggregate column, such as sum(), avg(), max(). The
official website says that SQL mode affects the syntax supported by MySQL and the data verification checks it performs, This makes it easier to use MySQL in different environments and other database servers

Official website reference link: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-setting

Solution:

1. It is found that the set global setting in MySQL does not take effect and cannot be set under my.cnf

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

2. Query again is normal

mysql> select * from fruits group by s_id,f_name;
+------+------+------------+---------+
| f_id | s_id | f_name     | f_price |
+------+------+------------+---------+
| a1   |  101 | apple      |    5.20 |
| b1   |  101 | blackberry |   10.20 |
| c0   |  101 | cherry     |    3.20 |
| t1   |  102 | banana     |   10.30 |
| t2   |  102 | grape      |    5.30 |
| bs1  |  102 | orange     |   11.20 |
| a2   |  103 | apricot    |    2.20 |
| o2   |  103 | coconut    |    9.20 |
| b2   |  104 | berry      |    7.60 |
| l2   |  104 | lemon      |    6.40 |
| bs2  |  105 | melon      |    8.20 |
| m2   |  105 | xbabay     |    2.60 |
| m3   |  105 | xxtt       |   11.60 |
| m1   |  106 | mango      |   15.70 |
| t4   |  107 | xbababa    |    3.60 |
| b5   |  107 | xxxx       |    3.60 |
+------+------+------------+---------+

sql_Mode interpretation:

ONLY_FULL_GROUP_BY: For the GROUP BY aggregation operation, if the column in the SELECT is not in the GROUP
Appears in BY, then this SQL is illegal, because the column is not in the GROUP BY clause
 
NO_AUTO_VALUE_ON_ZERO: This value affects the insertion of self-growing columns. By default, inserting 0 or NULL means that the next self-increasing value is generated. If the user
Hope that the inserted value is 0, and the column is self-increasing, then this option is useful.
 
STRICT_TRANS_TABLES: In this mode, if a value cannot be inserted into a transaction table, the current operation is interrupted, and there is no restriction on non-transactional tables
NO_ZERO_IN_DATE: In strict mode, the date and month are not allowed to be zero
 
NO_ZERO_DATE: Set this value. The mysql database does not allow the insertion of a zero date. Inserting a zero date will throw an error instead of a warning.
 
ERROR_FOR_DIVISION_BY_ZERO: During INSERT or UPDATE, if the data is divided by zero, an error is generated instead of a warning. like
If the mode is not given, then MySQL returns NULL when the data is divided by zero
 
NO_AUTO_CREATE_USER: prohibit GRANT from creating users with empty passwords
 
NO_ENGINE_SUBSTITUTION:
If the required storage engine is disabled or not compiled, then an error is thrown. When this value is not set, replace with the default storage engine and throw an exception
 
PIPES_AS_CONCAT:
Treat "||" as a string concatenation operator instead of an OR operator, which is the same as the Oracle database and similar to the string concatenation function Concat
 
ANSI_QUOTES: When ANSI_QUOTES is enabled, double quotes cannot be used to quote a string because it is interpreted as an identifier

GCC compilation error unknown type name ‘bool’‘

Error description

unknown type name ‘bool’

Recently, using C to implement data structure encountered the following error

➜  LinkedList gcc list.c 
list.c:14:1: error: unknown type name ‘bool’; did you mean ‘_Bool’?
 bool is_empty(PNODE pHead);
 ^~~~
 _Bool
list.c:77:1: error: unknown type name ‘bool’; did you mean ‘_Bool’?
 bool is_empty(PNODE pHead)
 ^~~~
 _Bool
list.c: In function ‘is_empty’:
list.c:80:9: error: ‘true’ undeclared (first use in this function); did you mean ‘free’?
  return true;
         ^~~~
         free
list.c:80:9: note: each undeclared identifier is reported only once for each function it appears in
list.c:82:9: error: ‘false’ undeclared (first use in this function); did you mean ‘fclose’?
  return false;
         ^~~~~

Error reason

Unknown type name: ‘bool’, because there is no boolean type defined in the C language standard (C89), an error will be reported. C99 provides a header file & lt; stdbool.h> defines bool , true represents 1 and false represents 0. As long as you import stdpool. H , you can easily operate Boolean types.

resolvent

#include <stdbool.h>

"21442;" 32771;"38142;" 25509

https://www.jianshu.com/p/aa951e784e96

When C language refers to a user-defined type as a parameter, an error segmentation fault is reported

Problem Description:

In the data structure operation, a function to initialize the table is written:


#define InitSize 100
#define ElemType int

typedef struct {
    ElemType* list;
    int len;
    int size;
} sql_;


int sql_init(sql_ *head) {
    (*head).list = (ElemType*)malloc(InitSize*sizeof(ElemType));
    (*head).len = 0;
    (*head).size = InitSize;

    return 1;
}

int main() {
    sql_ L1;
    sql_init(&L1);

    sql_*L2;
    sql_init(L2);

    system("pause");
}

However, an error is reported at runtime: segmentation fault

  After entering the debugging interface, it is found that L1 has been initialized successfully, but there is a problem when it comes to L2. What is the difference between L1 and L2 initialization codes?

Analyze the problem:

    sql_ L1;
    sql_init(&L1);

    sql_*L2;
    sql_init(L2);

It can be seen that L1 is declared as SQL_ Type; L2 is declared as SQL*_ Type.

There is no warning in vscode, but there is a warning and error in vs2019, and it can not even be compiled. So what’s the reason?

Through network retrieval, we get such an article: int * a in C + +; int & a; int & * a; int * & a_ Tianya Mingyue Dao blog – CSDN blog

Inspired by the quoted concepts mentioned in the article, we made the following attempts:

sql_ L;
    sql_*L2 = &L;
    sql_init(L2);

  After such processing, the initialization can be completed successfully. Therefore, the following guess is made:

When defining a macro type, only SQL is declared_ Type, but for SQL_* The type is not declared, so it is declared in main   sql_  *  L1; The compiler can’t find the prototype, so it can’t reference SQL when declaring parameters_* Type, so vs the more stringent compiler found this problem and told L2 that memory could not be allocated.

resolvent:

Using predefined SQL_ Type declaration, use its reference when parameters need to be passed & amp; L as SQL_* Arguments of type, that is, the method of initializing L1 mentioned earlier:

    sql_ L1;
    sql_init(&L1);

Solution to the segmentation fault of single chain table in C language

The title is a collection of single linked list operations, including the establishment, deletion, insertion, printing, release and other operations of linked list.

The code runs correctly in CodeBlocks, and an error is displayed when it is submitted to the OJ platform of the school.

The segmentation fault section is wrong, mainly because the array is out of bounds, the pointer is abnormal, and the memory area that should not be accessed is accessed. Single linked list mainly involves pointer operation. After checking that the array is correct (not used in this topic), it mainly checks the pointer.

This is the previous code:

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

typedef struct student
{
    long int num;
    float score;
    struct student *next;
}Node,*Link;

Link creatlink(void)
{
    Link head,node,rear;
    long int p;
    float q;
    head = (Link)malloc(sizeof(Node));
    head -> next = NULL;
    rear = head;
    while(scanf("%ld %f",&p,&q))
    {
        if(p == 0&&q == 0)
        {
            break;
        }
        node = (Link)malloc(sizeof(Node));
        node -> num = p;
        node -> score = q;
        rear -> next = node;
        rear = node;
    }
    rear -> next = NULL;
    return head;
}

void printlink(struct student *head)
{
    Link p;
    p = head -> next;
    while(p != NULL)
    {
        printf("%ld %.2f\n",p -> num,p -> score);
        p = p -> next;
    }
}

Link dellink(Link head,long int k)
{
    if(head == NULL||head -> next == NULL)
        exit(0);
    Link p,q;
    p = head -> next;
    q = head;
    while(p != NULL)
    {
        if(p -> num == k)
        {
            q -> next = p -> next;
            free(p);
        }
        else
        {
            q = p;
            p = p -> next;
        }
    }
    return head;
}

Link insertlink(Link head,Link stu)
{
    Link p,node,q;
    p = head;
    q = p -> next;
    while(q != NULL&&q -> num < stu -> num)
    {
        p = p -> next;
        q = p -> next;
    }
    if(q == NULL)
        p -> next = NULL;
    node = (Link)malloc(sizeof(Node));
    node -> num = stu -> num;
    node -> score = stu -> score;
    node -> next = p -> next;
    p -> next = node;
    return head;
}

void freelink(Link head)
{
    Link p;
    while(p != NULL)
    {
        p = head;
        head = head -> next;
        free(p);
    }
}

int main()
{
    struct student *createlink(void);
    struct student *dellink(struct student *, long);
    struct student *insertlink(struct student *, struct student *);
    void printlink(struct student *);
    void freelink(struct student *);
    struct student *head, stu;
    long del_num;
    head= creatlink();
    scanf("%ld", &del_num);
    head= dellink(head, del_num);
    scanf("%ld%f", &stu.num, &stu.score);
    head= insertlink(head, &stu);
    scanf("%ld%f", &stu.num, &stu.score);
    head= insertlink(head, &stu);
    printlink(head);
    freelink(head);
    return 0;
}

After excluding the error of other functions, it is finally found that the error occurs in the most insignificant release linked list function. It is found that the while loop end flag is wrong, and the head is always one step faster than the P pointer. If P= If NULL is the loop end flag, the loop is completed when the point pointed by the head is null and P points to the last node. At this time, P is not null, so the loop has to continue and the head has to move back. At this time, the head pointer becomes a wild pointer and has no point, so an error will be reported.

After modification, transpose the while loop end flag to head= Null, when p points to the last node and head is null, the node pointed to by P will be released, and the loop will end without wild pointer.

The modified release single linked list function is:

void freelink(Link head)
{
    Link p;
    while(head != NULL)
    {
        p = head;
        head = p -> next;
        free(p);
    }
}

After modification, submit it to OJ platform again and pass it correctly.

Leetcode error: address sanitizer: detailed analysis and solution of deadlysignal

Leetcode error: address sanitizer: detailed analysis and solution of deadlysignal

Problem description, problem analysis, case analysis, error source code, OK code after source code analysis and solution

For more summary, please refer to: C brush questions: leetcode brush questions step on the pit common bug summary

Problem description


Error: addresssanitizer: deadlysignal, details are as follows

===42====ERROR:AddressSanitizer: SEGV on unknown address xx. 
The signal is caused by a READ memory access.

Problem analysis


In general, there may be the following problems:

Out of bounds, the array reference exceeds the left and right bounds, infinite recursion, the code can not normally end, return function input and output parameters, return processing error

According to the above ideas, the example code is analyzed to solve the bug.

Case analysis


The questions come from leetcode topic 46. Please refer to the problem analysis blog for details. Paste the problem code of the above error in the first edition:

Error source code

Main key code of the first layer:

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int g_trackNum; // Used for temporary stacking during recursive calls
int g_rowPos;

// Subfunction declaration
int isContanin(int *nums, int len, int val);
void backtrack(int *nums, int numsSize, int **returnColumnSizes, int *track);

// Main call function
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
    // Calculate all possible totals
    int row = 1, i;
    for (i = numsSize; i > 0; i--) {
        row *= i;
    }
    *returnSize = row;

    printf("row = %d\n", row);

    // Request a two-dimensional array of the corresponding size and allocate space
    returnColumnSizes = (int **)malloc((row + 10) * sizeof(int*));
    if (returnColumnSizes == NULL) {
        return NULL;
    }
    int *p;
    for (i = 0; i < row; i++) {
        p = (int*)malloc((numsSize + 10) * sizeof(int));
        if (p == NULL) {
            return NULL;
        }
        returnColumnSizes[i] = p;
    }
    p = (int*)malloc(numsSize * sizeof(int));
    if (p == NULL) {
        return NULL;
    }
    int *track = p;

    // Backtrack to exhaust all possible permutations
    g_trackNum = 0;
    g_rowPos = 0;
    backtrack(nums, numsSize, returnColumnSizes, track); // Put the result from line 0

    // Returns returnSize and a two-dimensional pointer
    return returnColumnSizes;
}

Recursive code for backtracking implementation:

void backtrack(int *nums, int numsSize, int **returnColumnSizes, int *track)
{
    // Reach the leaf node track join returnColumSizes, the recorded path has been equal to the length of the array stop
    int i;
    if (g_trackNum == numsSize) {
        // printf("back: g_rowPos = %d\n", g_rowPos);
        for (i = 0; i < numsSize; i++) {
            // printf("back: g_rowPos = %d\n", g_rowPos);
            returnColumnSizes[g_rowPos][i] = track[i];
        }
        g_rowPos++;
        return;
    }

    // Recursive traversal
    for (i = 0; i < numsSize; i++) {
        // check if the current value is in the track
        if (isContanin(track, g_trackNum, nums[i])) {
            continue;
        }

        // If not, join track
        // printf("back: g_trackNum = %d\n", g_trackNum);
        track[g_trackNum++] = nums[i];
        
        // Continue traversing backwards
        backtrack(nums, numsSize, returnColumnSizes, track);
        // After the node returns, retrieve the value in the track
        g_trackNum--;
    }

    return;
}

Sub function to determine whether the current value has been traversed

int isContanin(int *nums, int len, int val)
{
    int flag = 0;
    int i;
    for (i = 0; i < len; i++) {
        if (nums[i] == val) {
            flag = 1;
            break;
        }
    }
    return flag;
}

Source code analysis

check possible problem 1 : out of bounds, array reference out of bounds

There are two main ideas:
1. Try to allocate enough space first to see if it is a space problem
2. Print subscript value in advance where it may cross the boundary to see if it overflows. Because address disinfection is interrupted at runtime, you can use printf to print the situation before the interruption.

Method 1

At each possible cross-border reference, the subscript is printed in advance to record the subscript coefficient printed before the program crashes. An example of the printing code is as follows: printf ("row = D/N", row)printf("back: g_ rowPos = %d\n", g_ rowPos);printf("back: g_ trackNum = %d\n", g_ trackNum);

Method 2

When initializing the array allocation space, forcibly allocates enough space to ensure that the space is sufficient. If there is no error after increasing the space, it means that the array reference is out of bounds

After running the code, it was found that subscript printing was normal, and no problem was found, so we continued to investigate possible problem 2.

check possible problem 2 : infinite recursion, the code can’t end and return normally

Print the output record directly in the termination condition of the recursive function backtrack, and observe whether the recursion is carried out according to the expected recursion mode. If there is no print record, then the function is not terminated and recursion is infinite all the time

After running the code, it is found that there is no such problem.

check possible problem 3 : error in the return processing of function input and output parameters
after carefully reading the input and output instructions of the first line of the code and comparing the implementation of online C code, it is found that the understanding of output parameters is wrong.

Variable secondary pointer returncolumnsizes stores the number of columns output in each row. Although the number of columns in the title is fixed, it needs to be assigned to the corresponding number of columns. And I first understood that this is the return pointer of a two-dimensional array. The return pointer of the two-dimensional array is passed through the function return parameter. The first address of the two-dimensional array allocated by direct return can be used.

After modifying the above problems, the code output is normal and no error is reported.

OK code after solution

// Determine if an element has been traversed
int isContain(int *nums, int len, int val)
{
    int flag = 0;
    int i;
    for (i = 0; i < len; i++) {
        if (nums[i] == val) {
            flag = 1;
            break;
        }
    }
    return flag;
}

// Note that this global variable is best defined by declaration only and initialized before backtrack
// in case the LeetCode judge does not re-initialize it, resulting in a miscalculation
int g_trackNum; // Used for temporary stacking during recursive calls
int g_rowPos; // Record each row

void backtrack(int *nums, int numsSize, int **returnColumnSizes, int *track)
{
    // Reach the leaf node track join returnColumSizes, the recorded path has been equal to the length of the array stop
    int i;
    if (g_trackNum == numsSize) {
        for (i = 0; i < numsSize; i++) {
            returnColumnSizes[g_rowPos][i] = track[i];
        }
        g_rowPos++;
        return;
    }

    // Recursive traversal
    for (i = 0; i < numsSize; i++) {
        // check if the current value is in the track
        if (isContain(track, g_trackNum, nums[i])) {
            continue;
        }

        // If not, add track
        track[g_trackNum++] = nums[i];
        // continue traversing backwards
        backtrack(nums, numsSize, returnColumnSizes, track);
        // After the node returns, retrieve the value in track
        g_trackNum--;
    }

    return;
}

int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
    // Calculate the total number of all possible n!
    int row = 1, i;
    for (i = numsSize; i > 0; i--) {
        row *= i;
    }
    *returnSize = row;

    // Calculate the number of columns in each row of the returned array
    *returnColumnSizes = (int *)malloc(sizeof(int) * (*returnSize));
    if (returnColumnSizes == NULL) {
        return NULL;
    }
    for (int i = 0; i < row; i++) {
        returnColumnSizes[0][i] = numsSize;
    }

    // Request a two-dimensional array of the corresponding size and allocate space
    int **res = (int **)malloc((row + 10) * sizeof(int*));
    if (res == NULL) {
        return NULL;
    }
    int *p;
    for (i = 0; i < row; i++) {
        p = (int*)malloc((numsSize + 10) * sizeof(int));
        if (p == NULL) {
            return NULL;
        }
        res[i] = p;
    }
    p = (int*)malloc(numsSize * sizeof(int));
    if (p == NULL) {
        return NULL;
    }
    int *track = p;

    // Backtrack to exhaust all possible permutations
    g_trackNum = 0;
    g_rowPos = 0;
    backtrack(nums, numsSize, res, track); // put the result from row 0

    return res;
}

C language: Implementation of dynamic array initialization, insertion, traversal, deletion and destruction

Initialization of dynamic array

#include <iostream>
using namespace std;
struct dynamicArray{ 
      void **pAddr;
      int m_capacity;
      int m_size;
      }
struct dynamicArray *initdynamicArray(int capacity){ 
         if(capacity<=0) {      
           return 0;
           }  
   struct dynamicArray *array=malloc(sizeof(struct dynamicArray)) 
   if(array=NULL){   
      return 0;
    }   
     array->pAddr=malloc(sizeof(void*)*capacity); 
     array->m_capacity=capacity;   
     array->size=0;    
     return array;
     }

Function series

```void *insert(struct dynamicArray *array,int pos,void *data){
if(array==NULL||data==NULL){
    return 0;
}
if(pos<=0||pos>array->m_size){
     pos=array->m_size;
}
if(array->m_size==array->capacity){
     int newCapacity=array->capacity;
     void **newSpace=malloc(sizeof(void*)*newCapacity);
     memcpy(newSpace,array->pAddr,sizeof(void *)*array->capacity);
     free(array->pAddr);
     array->pAddr=newSpace;
}

for(int i=array->m_size;i<=pos;i--){
     array->pAddr[i+1]=array->pAddr[i];
}

array->pAddr[pos]=data;

void foreach_Dynamicarray(struct dynamicArray *array,void(myPrint)(void*)){
     for(int i=0;i<array->m_size;i++){
     myPrint(array->pAddr[i]);
     }
 }
 void myPrintPerson(void *data){
     struct person *p=data;
     cout<<p->blabla<p->blabuble<endl;
 }

 void remove(struct dynamicArray *array,int pos){
     if(array==NULL||pos<=0||pos>=array->){
      return 0;
   }
   for(int i=array->m_size;i>=pos;i--){
       array->pAddr[i]=array->pAddr[i+1];
   }
 }

 void destroy(struct dynamicArray *array){
    if(array=NULL){
        return 0;
    }
    if(array->pAddr!=NULL){
        free(array->pAddr);
        array->pAddr=NULL;
    }
    free(array);
    array=NULL;
 }

Common attributes and methods of list and map in Dar

list common properties and methods

common property

1,length gets the length of list

main() {
  var list = ['red','yellow','pink'];
  print(list.length);
}

2, judge whether it is empty

main() {
  var list = ['red','yellow','pink'];
  print(list.isEmpty);
}

3, not null

main() {
  var list = ['red','yellow','pink'];
  print(list.isNotEmpty);
}

4, the array flips

main() {
  var list = ['red','yellow','pink'];
  print(list.reversed.toList());
}
(pink, yellow, red)

common method

1, add data

main() {
  var list = ['red','yellow','pink'];
  list.add("green");
  print(list);
}
[red, yellow, pink, green]

2, find data indexOf, find return index, can’t find return -1

main() {
  var list = ['red','yellow','pink'];
  var res = list.indexOf('yellow');
  print(res);

}  

1

3, removed data (‘ value ‘),removeAt(index)

main() {
  var list = ['red','yellow','pink'];
  list.remove('yellow');
  list.removeAt(1);

  print(list);

}  
[red]

4, modify data fillRange(start,end,value) without end

main() {
  var list = ['red','yellow','pink'];
  list.fillRange(1, 2,'green');
  print(list);

}

[red, green, pink]

5, insert data insert(index,value) to the specified position. Insert

from index

main() {
  var list = ['red','yellow','pink'];
  list.insert(1, 'green');
  print(list);
}

[red, green, yellow, pink] 

main() {
  var list = ['red','yellow','pink'];
  list.insertAll(1, ['green','white']);
  print(list);
  
} 
[red, green, white, yellow, pink]

6, convert to string join(‘, ‘), instead of the original list

main() {
  var list = ['red','yellow','pink'];
  var str = list.join(',');
  print(str);

}
 
red,yellow,pink

7, convert string to array split(‘ – ‘), do not change the original string

main() {
  var str = 'red-yellow-pink';
  var list = str.split('-');
  print(list);
  print(str);
  
}  
[red, yellow, pink]
red-yellow-pink

8, for(var item in list) loop list

main() {
  var list = ['red','yellow','pink'];
  for(var item in list) {
    print(item);
  }
}

red
yellow
pink

9,map loop list

main() {
  var list = [1,2,3,4];
  var newList = list.map((value) => value * 2);
  print(newList.toList());
}

10, see if the set satisfies some condition any

main() {
  var list = ['red','yellow','pink'];
  var f = list.any((value) => value == 'red');
  print(f);
  print(list);
  
}

11, through the set can not add repeated collection, so can not get

through the index

main() {
  var set = new Set();
  set.add('red');
  set.add('yellow');
  set.add('pink');
  set.add('red');
  print(set.toList());
}  

[red, yellow, pink]

maps type common properties and methods

1, get all keys

main() {
  var person = {
    'name':'张三',
    'age':20,
  };
  print(person.keys.toList());
}

[name, age]

2, get all values

main() {
  var person = {
    'name':'张三',
    'age':20,
  };
  print(person.values.toList());
}

3, determine whether the attribute isEmpty isEmpty

main() {
  var person = {
    'name':'张三',
    'age':20,
  };
  print(person.isEmpty);
  
}
false

common method

1, remove the specified key data (key)

main() {
  var person = {
    'name':'张三',
    'age':20,
  };
  person.remove('name');
  print(person);
}
{age: 20}

2, addAll({‘ key ‘:’ value ‘})

main() {
  var person = {
    'name':'张三',
    'age':20,
  };
  person.addAll({
    'sex':'男',
  });
  print(person);
}

{name: 张三, age: 20, sex: 男}

3, check to see if the fields are in the map containsKey(key), return true/false does not change the original pair like

main() {
  var person = {
    'name':'张三',
    'age':20,
  };
  var boo = person.containsKey('name');
  print(boo);

}

true

blog address
related documents
github document address

Java foundation — printing Yang Hui triangle

problem: print out a 10-line yanghui triangle
point: two-dimensional array
idea: first analyze the law of yanghui triangle: 1. 2. Each line ends with a 1; 3. Starting from the third row, every non-first and last number is: yangHui[I][j]=yangHui[i-1][j-1]+yangHui[i-1][j]. The code is:

//        1.声明初始化二维数组
        int[][] yangHui = new int[10][];
//        2.给数组的元素赋值
        for (int i = 0; i < yangHui.length; i++) {
            yangHui[i] = new int[i+1];
//            2.1 给首末元素赋值
            yangHui[i][0] = 1;
            yangHui[i][i] = 1;
//            2.2 给每行的非首末元素赋值
            if (i>1){
                for (int j = 1; j <yangHui[i].length-1 ; j++) {
                    yangHui[i][j]=yangHui[i-1][j-1]+yangHui[i-1][j];
                }
            }
        }
        
//        3.遍历二维数组
        for (int i = 0; i < yangHui.length; i++) {
            for (int j = 0; j <yangHui[i].length ; j++) {
                System.out.print(yangHui[i][j]+"\t");
            }
            System.out.println();
        }

Output:

1 1 1 2 1 1 3 3 1

1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28日8 1
1 9 36 84 126 126 84 36 9 1