Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3346674
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T01:19:55+00:00 2026-05-18T01:19:55+00:00

Intro to problem: I am given recipes how to craft items. Recipe is in

  • 0

Intro to problem:

I am given recipes how to craft items. Recipe is in format : {element that is being crafter}: {list of elements, that is needed}. Before I can craft element x, I need to know how to craft elements it’s made of. So I want to find in what order do I have to learn recipes.

For valid input, like following everything works:

// Input:
{ 
    "F1: F2 F3 F4", "F5: F6 F4", "F6: F7 F8 F4", "F2: F3 F8 F4", "F8: F4",
    "F9: F4", "F7: F4", "F10: F7 F4", "F11: F4", "F4:", "F3: F6"
}
// Output:
[F4, F7, F8, F6, F3, F2, F1, F5, F9, F10, F11]

The problem is, that task is more complex. Time to time I have some recipes missing or thy are invalid. Example of invalid input: { "F1: F2", "F2: F1" }.

Code example:

mp contains recipe name as key and elements as value, labels are unique mp keys and result will contain answer. I’m looking for a way to return empty result if infinite loop is met.

private void getArray(HashMap<String, ArrayList<String>> mp,
        ArrayList<String> result, ArrayList<String> labels) {
    for (String a : labels) {
        if (mp.get(a) != null)
            for (String label : mp.get(a))
                getArray(mp, result, label);
        if (!result.contains(a))
            result.add(a);
    }
}

private void getArray(HashMap<String, ArrayList<String>> mp,
        ArrayList<String> result, String label) {
    if (result.contains(label))
        return;
    if (mp.get(label) == null) {
        result.add(label);
        return;
    }
    for (String l : mp.get(label))
        getArray(mp, result, l);
    if (!result.contains(label))
        result.add(label);
}

Edit

Problem solved.

For any Google’s that stumble up this, this is what I came up with:

/** <p>
 * <b>Topological sort</b> solves a problem of - finding a linear ordering
 * of the vertices of <i>V</i> such that for each edge <i>(i, j) ∈ E</i>,
 * vertex <i>i</i> is to the left of vertex <i>j</i>. (Skiena 2008, p. 481)
 * </p>
 * 
 * <p>
 * Method is derived from of <a
 * href="http://en.wikipedia.org/wiki/Topological_sort#Algorithms" > Kahn's
 * pseudo code</a> and traverses over vertices as they are returned by input
 * map. Leaf nodes can have null or empty values. This method assumes, that
 * input is valid DAG, so if cyclic dependency is detected, error is thrown.
 * tSortFix is a fix to remove self dependencies and add missing leaf nodes.
 * </p>
 * 
 * <pre>
 * // For input with elements:
 * { F1=[F2, F3, F4], F10=[F7, F4], F11=[F4], F2=[F3, F8, F4], F3=[F6], 
 *   F4=null, F5=[F6, F4], F6=[F7, F8, F4], F7=[F4], F8=[F4], F9=[F4]}
 *   
 * // Output based on input map type: 
 * HashMap: [F4, F11, F8, F9, F7, F10, F6, F5, F3, F2, F1]
 * TreeMap: [F4, F11, F7, F8, F9, F10, F6, F3, F5, F2, F1]
 * </pre>
 * 
 * @param g
 *            <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph"
 *            > Directed Acyclic Graph</a>, where vertices are stored as
 *            {@link java.util.HashMap HashMap} elements.
 * 
 * @return Linear ordering of input nodes.
 * @throws Exception
 *             Thrown when cyclic dependency is detected, error message also
 *             contains elements in cycle.
 * 
 */
public static <T> ArrayList<T> tSort(java.util.Map<T, ArrayList<T>> g)
        throws Exception
/**
 * @param L
 *            Answer.
 * @param S
 *            Not visited leaf vertices.
 * @param V
 *            Visited vertices.
 * @param P
 *            Defined vertices.
 * @param n
 *            Current element.
 */
{
    java.util.ArrayList<T> L = new ArrayList<T>(g.size());
    java.util.Queue<T> S = new java.util.concurrent.LinkedBlockingDeque<T>();
    java.util.HashSet<T> V = new java.util.HashSet<T>(), 
    P = new java.util.HashSet<T>();
    P.addAll(g.keySet());
    T n;

    // Find leaf nodes.
    for (T t : P)
        if (g.get(t) == null || g.get(t).isEmpty())
            S.add(t);

    // Visit all leaf nodes. Build result from vertices, that are visited
    // for the first time. Add vertices to not visited leaf vertices S, if
    // it contains current element n an all of it's values are visited.
    while (!S.isEmpty()) {
        if (V.add(n = S.poll()))
            L.add(n);
        for (T t : g.keySet())
            if (g.get(t) != null && !g.get(t).isEmpty() && !V.contains(t)
                    && V.containsAll(g.get(t)))
                S.add(t);
    }

    // Return result.
    if (L.containsAll(P))
        return L;

    // Throw exception.
    StringBuilder sb = new StringBuilder(
            "\nInvalid DAG: a cyclic dependency detected :\n");
    for (T t : P)
        if (!L.contains(t))
            sb.append(t).append(" ");
    throw new Exception(sb.append("\n").toString());
}

/**
 * Method removes self dependencies and adds missing leaf nodes.
 * 
 * @param g
 *            <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph"
 *            > Directed Acyclic Graph</a>, where vertices are stored as
 *            {@link java.util.HashMap HashMap} elements.
 */
public static <T> void tSortFix(java.util.Map<T, ArrayList<T>> g) {
    java.util.ArrayList<T> tmp;
    java.util.HashSet<T> P = new java.util.HashSet<T>();
    P.addAll(g.keySet());

    for (T t : P)
        if (g.get(t) != null || !g.get(t).isEmpty()) {
            (tmp = g.get(t)).remove(t);
            for (T m : tmp)
                if (!P.contains(m))
                    g.put(m, new ArrayList<T>(0));
        }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T01:19:55+00:00Added an answer on May 18, 2026 at 1:19 am

    The problem you are solving is known as topological sort. Kahn’s algorithm solves the problem while also detecting invalid input (that is, containing cycles).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here is a seemingly simple problem: given a list of iterators that yield sequences
Problem: Given : n points that are strongly correlated to a 3d k-sided non-convex
I have to solve the following optimization problem: Given a set of elements (E1,E2,E3,E4,E5,E6)
I've been given a problem that I need some assistance from the SO community
I have the following problem: I have a given number of identically formed items
I'm fairly new to using MSSQL and have run into a weird problem. Given
I just run into another problem with my To-do-like sortable list made with Knockout
I bumped into this problem when I created a chart that need a axis
I ran into a problem that suggests I may be implementing a design pattern
I have the following problem. I have an array of bytes that I want

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.