D
D
Dmitry072016-10-25 10:00:12
Java
Dmitry07, 2016-10-25 10:00:12

How to add missing elements to an array?

Good day.
There is a tree of elements, for example, directories. In the 'correct' form, it looks like this:
A1, A1\BB1, A1\BB1\CCC1, A2, A2\BB1, A2\BB1\CCC1
Algorithm for the arrangement of array elements: if there is an element A1\BB1\CCC1, then it is preceded by 'parent' elements A1\BB1 and A1.
The question is, if this array has missing elements, as in this case:
A1, A1\BB1\CCC1, A2\BB1, A2\BB1\CCC1
how to properly parse its strings in order to get the original form of the array again?
Thanks to.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Cheremisin, 2016-10-25
@Dmitry07

For example like this. Not optimized :-)

package my.com;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Paths {
  public static void main(String[] args) {
    String str = "A1, A1\\BB1\\CCC1, A2\\BB1, A2\\BB1\\CCC1";
    ArrayList<String> paths = new ArrayList<String>(Arrays.asList(str.split(",")));

    System.out.println("======  Беган =======");
    System.out.println("Было");
    for(String i:paths){
      System.out.println(i);
    }
    
    Set<String> out = new TreeSet<String>(new Comparator<String>() {

      @Override
      public int compare(String o1, String o2) {
        return o2.compareTo(o1);
      }
      
    });
    for(String i : paths) {
      ArrayList<String> path = new ArrayList<String>(Arrays.asList(i.trim().split("\\\\")));
  
      for(int j = 1; j <= path.size(); j++) {
        List<String> s = path.subList(0, j);
        out.add(String.join("\\",s));
      }
    }

    System.out.println("=================");
    System.out.println("Сортировка туда");
    for(String i:out) {
      System.out.println(i);
    }

    System.out.println("=================");
    System.out.println("Сортировка обратно");
    Set<String> out1 = new TreeSet<String>();
    out1.addAll(out);
    for(String i:out1) {
      System.out.println(i);
    }
    System.out.println("======= Доне ======");
    
  }
}

======  Беган =======
Было
A1
 A1\BB1\CCC1
 A2\BB1
 A2\BB1\CCC1
=================
Сортировка туда
A2\BB1\CCC1
A2\BB1
A2
A1\BB1\CCC1
A1\BB1
A1
=================
Сортировка обратно
A1
A1\BB1
A1\BB1\CCC1
A2
A2\BB1
A2\BB1\CCC1
======= Доне ======

A
Alexey, 2016-12-15
@AntonTitovI

Because you don't call it.
Add a line $a = $el->myValue;and $n will be printed.

A
Anton, 2016-12-15
@hummingbird

Precisely everything is fine (checked) according to the code?
php.net/manual/ru/language.oop5.overloading.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question