hscspring
I have a python code like this:
class Node:
def __init__(self, path: str):
self.path = path
self.children = {}
class MultiTree:
def __init__(self, root="/"):
self.root = Node(root)
def build(self, lst: list):
for p in lst:
f = p.split("/")
pointer = self.root
for i in range(1, len(f)):
path = "/".join(f[:i+1])
if path not in pointer.children:
node = Node(path)
pointer.children[path] = node
pointer = node
else:
pointer = pointer.children[path]
def dfs(self, root):
stack, res = [], []
stack.append(root)
while len(stack):
curr = stack.pop()
if curr.path not in res:
res.append(curr.path)
stack.extend(reversed(list(curr.children.values())))
return res
That’s a solution to construct a directory tree.
For example, given a dataset like:
list = [“/2/3”, “/2/4”, “/2/4/6”, “/2/3/7”, “/2/3/5”, “/2/3/8”]
the output of dfs will be:
[‘/’, ‘/2’, ‘/2/3’, ‘/2/3/7’, ‘/2/3/5’, ‘/2/3/8’, ‘/2/4’, ‘/2/4/6’]
Now in Elixir, i don’t know how to return the root.
would anyone met the similar situation?
My solution is:
defmodule MultiTree do
defmodule Node do
defstruct path: nil, children: %{}
end
@root "/"
def tree_root(list) do
root = list
|> Enum.reduce(%Node{}, fn p, root ->
f = Enum.drop(String.split(p, "/"), 1)
build(f, f, root)
end)
%Node{ path: @root, children: root }
end
defp build([], full_list, root) do
root
end
defp build([_ | children], full_list, root) do
eol = Enum.count(full_list) - Enum.count(children)
path = "/" <> Enum.join(Enum.slice(full_list, 0..eol-1), "/")
%Node{path: path, children: build(children, full_list, root)}
end
def dfs() do
end
end
However, there’s a problem… The keys are duplicated, for example:
list = ["/2/3", "/2/4", "/2/3/5"]
tree = MultiTree.tree_root(list)
IO.inspect(tree)
The output is:
%MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{
children: %MultiTree.Node{children: %{}, path: nil},
path: "/2/3"
},
path: "/2"
},
path: "/2/4"
},
path: "/2"
},
path: "/2/3/5"
},
path: "/2/3"
},
path: "/2"
},
path: "/"
}
The expected output should be:
path: "/":
children: {"/2":
{path: "/2",
children: {"/2/3": {path: "/2/3",
children: {"/2/3/4": {path: "/2/3/4", children: {}},
{"/2/3/5}: {path: "/2/3/5", children: {}}
},
},
"/2/4": {path: "/2/4", children: {} }}}}
I also wrote a non-recursion one:
def build_tree(list) do
root = list
|> Enum.reduce(%Node{}, fn p, root ->
f = Enum.drop(String.split(p, "/"), 1)
pointer = root
Enum.reduce(1..Enum.count(f), fn i, _ ->
path = Enum.join(Enum.slice(f, 0..i+1), "/")
ele = Map.get(pointer.children, path)
pointer =
if ele == nil do
node = %Node{ path: path }
Map.put(pointer.children, path, node)
node
else
ele
end
end)
end)
%Node{ path: @root, children: root }
end
however it’s not right…
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New
Hello,
I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter).
The diffic...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #phoenix_html
- #iex
- #elixirconf-us
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
NobbZ
What have you tried in elixir so far?
I have not tried to solve that exercise yet, but from a first glance it should be a matter of splitting and grouping and mearging back…
hscspring
Actually, i have used almost the same code like given above.
Clearly that’s not a good solution (and there is also a bug, i’m trying to fix it).
And i’m now reading several Elixir books and searching the web.
When i’ve finished the code, i’ll post it here~
thanks;)
hscspring
@Nobbz I have updated the code~
hscspring
@ benwilson512
would u please do me a fever?
I have done my best…
mudasobwa
In the first place your expected output is invalid because the node might obviously have several children. One might introduce another struct for children. or have a map
path → childthere. If the latter approach is ok, I’d go withAccessimplementation to ease operations upon this tree afterwards:Of course, the code might be tweaked further to implement
Inspectprotocol for the better representation etc.hscspring
Thanks a lot.
I’m trying .
Qqwy
Here is another approach, using a nested map of maps as tree representation.
I have documented the code to make it hopefully easy to understand.
mudasobwa
hscspring
That’s very clear, thanks very much .
There’s another point: the given list is ordered.
for example, gievn list = [“/2/3”, “/2/4”, “/2/4/6”, “/2/3/7”, “/2/3/5”, “/2/3/8”]
output is [’/’, ‘/2’, ‘/2/3’, ‘/2/3/7’, ‘/2/3/5’, ‘/2/3/8’, ‘/2/4’, ‘/2/4/6’]
“/2/3/7” is ahead of “/2/3/5”.
so, I have to do some sort when building the tree or traveling it.
Actually the task is something below:
Given a list of items, each item with a directory and a create_time, my task is to sort those items by two rules:
Here is a real task example:
The final expected order is
Let me expain
“/folder1”, “/folder2” and “/folder3” are not in the index_dict, so they are sorted by create_time:
“/folder2” > “/folder3” > “/folder1”
then, Let’s loot at the subfolders of folder2
“/folder2/folder2-folder1” and “/folder2/folder2-folder2” are also not in the index_dict (values), so they are sorted by create_time
“/folder2/folder2-folder2” > “/folder2/folder2-folder1”
then, their subdirectories (here are files)
although “/folder2/folder2-folder1/file2” > “/folder2/folder2-folder1/file1” by create_time, in the index_dict, “file1” > “file2”, so the result is ‘/folder2/folder2-folder1/file1’ > ‘/folder2/folder2-folder1/file2’.
Another example, let’s look at folder3, they have sub folders in the index_dict, so sub folders need to be sorted like that
‘/folder3/folder3-folder1’ > ‘/folder3/folder3-folder2’, then ‘/folder3/folder3-folder4’ > ‘/folder3/folder3-folder3’, by their create_time.
My python code is
I have written this task with python in three different ways
However, i can’t do it by Elixir, i am really frustrated though i am new to it…
Maybe i need some more exercise…
If anyone who met this issue before, i feel grateful if you give me some advice.
hscspring
Thanks a lot~
There are several things i didn’t understand, so i have spent some time to learn.
I have tried the code, when i given another different ordered list, like: [“/2/3/8”, “/2/3”, “/2/4”, “/2/4/6”, “/2/3/7”, “/2/3/5”], the result seems a little weird…