Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Index erstellen (Felder)

Schreiben Sie ein Programm, das aus einer Definitionsliste einen Index erstellt. Die Defininionsliste besteht aus mehreren Zeilen. Jede Zeile beschreibt eine Definition. Zuerst kommt der Definitionsterm gefolgt von einem Doppelpunkt. Danach erscheinen (mit Kommata getrennt) die definierenden Begriffe. Gleich zwei Beispiele:

Erstes Beispiel:

Blume: Blatt, Stiel, Blüte, Grün
Baum: Stamm, Ast, Blüte, Grün, Blatt
Pilz: Hut, Farbe, Stiel

Zweites Beispiel:

Tisch: Holz, Beine
Schrank: Holz, Tür
Stuhl: Lehne, Beine, Sitzfläche
Bett: Holz, Beine, Laken

Solche Definitionslisten soll Ihr Programm nun indexieren können. Dabei stehen dann zunächst die definierenden Begriffe gefolgt von einem Doppelpunkt. Rechts des Dopplepunktes stehen danach die Definitionsterme (wieder Kommata getrennt). Gleich wieder unsere Beispiele:

Index zum 1. Beispiel:

Blatt: Blume, Baum
Stiel: Blume, Pilz
Blüte: Blume, Baum
Grün: Blume, Baum
Stamm: Baum
Ast: Baum
Hut: Pilz
Farbe: Pilz

Index zum 2. Beispiel:

Holz: Tisch, Schrank, Bett
Beine: Tisch, Stuhl, Bett
Tür: Schrank
Lehne: Stuhl
Sitzfläche: Stuhl
Laken: Bett

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

7 Lösung(en)

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

static void *malloc_fatal(size_t sz)
{
	void *p = malloc(sz);

	if (!p) {
		fprintf(stderr, "malloc(%lu) failed\n", (unsigned long) sz);
		exit(EXIT_FAILURE);
	}

	return p;
}

static char *strdup_fatal(const char *str)
{
	char *s = strdup(str);

	if (!s) {
		fprintf(stderr, "strdup(\"%s\") failed\n", str);
		exit(EXIT_FAILURE);
	}

	return s;
}

struct child {
	struct child *next;
	char *name;
};

struct parent {
	struct parent *next;
	struct child *first_child;
	struct child *last_child;
	char *name;
};

static struct parent *first_parent;
static struct parent *last_parent;

static struct parent *find_or_add_parent(const char *name)
{
	struct parent *p;

	for (p = first_parent; p; p = p->next)
		if (!strcmp(p->name, name))
			return p;

	p = malloc_fatal(sizeof(*p));
	p->name = strdup_fatal(name);
	p->first_child = NULL;
	p->last_child = NULL;

	if (first_parent) {
		last_parent->next = p;
		last_parent = p;
	} else {
		first_parent = p;
		last_parent = p;
	}

	return p;
}

static struct child *find_or_add_child(struct parent *parent, const char *name)
{
	struct child *p;

	for (p = parent->first_child; p; p = p->next)
		if (!strcmp(p->name, name))
			return p;

	p = malloc_fatal(sizeof(*p));
	p->name = strdup_fatal(name);

	if (parent->first_child) {
		parent->last_child->next = p;
		parent->last_child = p;
	} else {
		parent->first_child = p;
		parent->last_child = p;
	}

	return p;
}

static void find_or_add(const char *parent_name, const char *child_name)
{
	struct parent *parent;

	parent = find_or_add_parent(parent_name);
	find_or_add_child(parent, child_name);
}

static int parse_forward;

static char *find_nonspace(char *s)
{
	while (isspace(*s))
		s++;
	return s;
}

static void parse_line(char *line)
{
	char *pos, *nul;
	char *parent, *child;

	pos = find_nonspace(line);
	if (!pos)
		return;

	nul = strchr(pos, ':');
	if (!nul)
		return;
	parent = pos;
	*nul = '\0';

	pos = nul + 1;

	for (;;) {
		pos = find_nonspace(pos);
		if (!pos)
			break;

		child = pos;
		nul = strchr(pos, ',');
		if (nul)
			*nul = '\0';
		if (parse_forward)
			find_or_add(parent, child);
		else
			find_or_add(child, parent);

		if (!nul)
			break;

		pos = nul + 1;
	}
}

static void parse_file(FILE *f)
{
	static char line[BUFSIZ];
	char *nl;

	for (;;) {
		if (!fgets(line, sizeof(line), f))
			break;

		nl = strchr(line, '\n');
		if (nl)
			*nl = '\0';

		parse_line(line);
	}
}

static void print_all(FILE *f)
{
	struct parent *p;
	struct child *c;
	int not_first_child;

	for (p = first_parent; p; p = p->next) {
		fprintf(f, "%s: ", p->name);
		not_first_child = 0;
		for (c = p->first_child; c; c = c->next) {
			if (not_first_child)
				fprintf(f, ", ");
			else
				not_first_child = 1;

			fprintf(f, "%s", c->name);
		}
		putc('\n', f);
	}
}

static void free_all(void)
{
	struct parent *p, *p_next;
	struct child *c, *c_next;

	for (p = first_parent; p; p = p_next) {
		for (c = p->first_child; c; c = c_next) {
			free(c->name);
			c_next = c->next;
			free(c);
		}
		free(p->name);
		p_next = p->next;
		free(p);
	}
}

static void parse_cmdline(int argc, char **argv)
{
	int i;

	if (argc < 2)
		return;

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--forward") || !strcmp(argv[i], "-f"))
			parse_forward = 1;
	}
}

int main(int argc, char **argv)
{
	parse_cmdline(argc, argv);

	parse_file(stdin);

	print_all(stdout);

	free_all();

	return EXIT_SUCCESS;
}

                

Lösung von: Jonathan Neuschäfer (St.-Bernhard-Gymnasium, 47877 Willich)

package ch.programmieraufgaben.index;

import java.io.*;
import java.util.*;

/**
 * @author Philipp Gressly (phi@gressly.ch)
 */
public class Index {
    public static void main(String args[]) {
        new Index().top("moebel");
        new Index().top("natur");
    }

    void top(String fileNameOhneSuffix) {
        try {
            String fileName = fileNameOhneSuffix + ".txt";
            FileReader input;
            input = new FileReader(fileName);
            indiziere(new LineNumberReader(input));
        } catch (FileNotFoundException e) {
            System.out.println("Datei " + fileNameOhneSuffix
                    + "(.txt) nicht gefunden.");
        } catch (IOException e) {
            System.out
                    .println("Fehler beim Lesen / Verarbeiten der Eingabedatei "
                            + fileNameOhneSuffix);
        }
    }

    // Jeweils das erste Wort in der Liste (index 0) ist der Begriff, die
    // nachfolgenden sind die Stichworte.
    ArrayList<ArrayList<String>> index = new ArrayList<ArrayList<String>>();

    void indiziere(LineNumberReader in) throws IOException {
        String line;
        while (null != (line = in.readLine())) {
            indiziere(line);
        }
        indexAusgeben();
    }

    void indexAusgeben() {
        for (ArrayList<String> stichwort : index) {
            stichwortAusgeben(stichwort);
        }
    }

    void stichwortAusgeben(ArrayList<String> stichwort) {
        System.out.print(stichwort.get(0) + ": ");
        for (int idx = 1; idx < stichwort.size(); idx++) {
            System.out.print(stichwort.get(idx));
            if (idx < stichwort.size() - 1) {
                System.out.print(", ");
            }
        }
        System.out.println();
    }

    void indiziere(String line) {
        int ddPos = line.indexOf(":");
        String begriff = line.substring(0, ddPos);
        String definitionen = line.substring(ddPos + 1);
        StringTokenizer defs = new StringTokenizer(definitionen, ",");
        while (defs.hasMoreTokens()) {
            String wort = defs.nextToken();
            fuegeDemIndexAn(begriff.trim(), wort.trim());
        }
    }

    void fuegeDemIndexAn(String begriff, String wort) {
        int idx = findeIndexOfWort(wort);
        ArrayList<String> stichwort;
        if (idx < 0) { // not found
            stichwort = new ArrayList<String>();
            stichwort.add(wort);
            stichwort.add(begriff);
            index.add(stichwort);
        } else { // found
            stichwort = index.get(idx);
            if (!existiertBegriffInStichwort(begriff, stichwort)) {
                stichwort.add(begriff);
            }
        }
    }

    boolean existiertBegriffInStichwort(String begriff,
            ArrayList<String> stichwort) {
        for (int idx = 1; idx < stichwort.size(); idx++) {
            if (begriff.equals(stichwort.get(idx))) {
                return true;
            }
        }
        return false;
    }

    int findeIndexOfWort(String wort) {
        for (int idx = 0; idx < index.size(); idx++) {
            ArrayList<String> stichwort = index.get(idx);
            if (wort.equals(stichwort.get(0))) {
                return idx;
            }
        }
        return -1;
    }

} // end of class Index
                

Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

// Copyright 2012, Christian J. Kiewiet.
//
///////////////////////////////////////////////////////////////////////////////
// Lösung zur Aufgabenstellung ``Index erstellen (Felder)''
//
// ``Schreiben Sie ein Programm, das aus einer Definitionsliste einen Index 
// erstellt. Die Defininionsliste besteht aus mehreren Zeilen. Jede Zeile 
// beschreibt eine Definition. Zuerst kommt der Definitionsterm gefolgt von 
// einem Doppelpunkt. Danach erscheinen (mit Kommata getrennt) die definierenden 
// Begriffe.''
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <map>
#include <set>
#include <boost/tokenizer.hpp>

/** Indexes a definition and its associations into a vector of sets.  Provides
 * a method to access the former. */
class Index {
  public:
    // Type that stores the index.
    typedef std::map<std::string, std::set<std::string>> IndexArray;
    
    /** Functor to quickly index a (definition, associations) pair.  This
     * assumes |assocations| to be a comma separated list of words. */
    void operator()(const std::string& definition, 
                    const std::string& associations) {
      boost::char_separator<char> separator(", ");
      boost::tokenizer<decltype(separator)> tokens(associations, separator);
      
      for (const auto& token : tokens)
        index_[token].insert(definition);
    }
    
    /** Retrieve |index_|. */
    inline const IndexArray& GetIndex() const { return index_; }
    
  private:
    IndexArray index_;
};  // class Index

                

Lösung von: Christian Kiewiet ()

using System;
using System.Collections.Generic;
using System.Linq;

namespace Index_Erstellen {
	class Program {
		static void Main(string[] args) {
			Dictionary<string, List<string>> 
				einträge = new Dictionary<string,List<string>>(),
				index = new Dictionary<string,List<string>>(),
				probe = new Dictionary<string,List<string>>();

			einträge.Add("Blume", new List<string>());
			einträge.LastOrDefault().Value.Add("Blatt");
			einträge.LastOrDefault().Value.Add("Stiel");
			einträge.LastOrDefault().Value.Add("Blüte");
			einträge.LastOrDefault().Value.Add("Grün");

			einträge.Add("Baum", new List<string>());
			einträge.LastOrDefault().Value.Add("Stamm");
			einträge.LastOrDefault().Value.Add("Ast");
			einträge.LastOrDefault().Value.Add("Blüte");
			einträge.LastOrDefault().Value.Add("Grün");
			einträge.LastOrDefault().Value.Add("Blatt");

			einträge.Add("Pilz", new List<string>());
			einträge.LastOrDefault().Value.Add("Hut");
			einträge.LastOrDefault().Value.Add("Farbe");
			einträge.LastOrDefault().Value.Add("Stiel");

			//Aufgabe
			foreach (KeyValuePair<string, List<string>> Eintrag in einträge) {
				foreach (string Wert in Eintrag.Value) {
					if (!index.ContainsKey(Wert))
						index.Add(Wert, new List<string>());

					if(!index[Wert].Contains(Eintrag.Key))
						index[Wert].Add(Eintrag.Key);
				}
			}

			//Ausgabe
			foreach (KeyValuePair<string, List<string>> Eintrag in einträge) {
				Console.Write("{0}: ", Eintrag.Key);
				foreach (string Wert in Eintrag.Value) {
					Console.Write("{0}{1}", Wert, Wert == Eintrag.Value.LastOrDefault() ? "" : ", ");
				}
				Console.WriteLine();
			}

			Console.WriteLine("");

			foreach (KeyValuePair<string, List<string>> Eintrag in index) {
				Console.Write("{0}: ", Eintrag.Key);
				foreach (string Wert in Eintrag.Value) {
					Console.Write("{0}{1}", Wert, Wert == Eintrag.Value.LastOrDefault() ? "" : ", ");
					
				}
				Console.WriteLine();
			}


			//Aufgabe: Probe
			Console.WriteLine("\n\nProbe:");

			foreach (KeyValuePair<string, List<string>> Eintrag in index) {
				foreach (string Wert in Eintrag.Value) {
					if (!probe.ContainsKey(Wert))
						probe.Add(Wert, new List<string>());

					if (!probe[Wert].Contains(Eintrag.Key))
						probe[Wert].Add(Eintrag.Key);
				}
			}

			//Ausgabe: Probe
			foreach (KeyValuePair<string, List<string>> Eintrag in probe) {
				Console.Write("{0}: ", Eintrag.Key);
				foreach (string Wert in Eintrag.Value) {
					Console.Write("{0}{1}", Wert, Wert == Eintrag.Value.LastOrDefault() ? "" : ", ");

				}
				Console.WriteLine();
			}

			Console.ReadKey(true);
		}
	}
}
                

Lösung von: Marcel Kapma ()

function Definition(name, terms) {
  this.name = name;
  this.terms = terms || [];
}

function DefinitionList() {
  this.defs = [];
  this.add = function(d) { this.defs.push(d); }
  this.printAll = function() {
    document.write("<p>");
    for (var i = 0; i < this.defs.length; i++) {
      document.write("<b>" + this.defs[i].name + ":</b> ");
      document.write(this.defs[i].terms.join(", ") + "<br>");
    }
    document.write("</p>");
  }
  this.index = function() {
    var collector = [],
        dl = new DefinitionList(),
        i, j;
    // terme sammeln
    for (var i = 0; i < this.defs.length; i++)
      collector = collector.concat(this.defs[i].terms);
    // collector sortieren und mehrfache einträge entfernen
    collector.sort(); i = 0;
    while (i < collector.length-1) {
      while (collector[i] == collector[i+1]) collector.splice(i+1, 1);
      i++;
    }
    // collector-elemente als namen setzen
    for (i = 0; i < collector.length; i++) {
      dl.add(new Definition(collector[i]));
      // terme für alle namen sammeln und hinzufügen
      for (j = 0; j < this.defs.length; j++) {
        if (this.defs[j].terms.indexOf(dl.defs[i].name) > -1)
          dl.defs[i].terms.push(this.defs[j].name);
      }
    }
    return dl;
  }
}
// tests
var list1 = new DefinitionList();
list1.add(new Definition("Blume", ("Blatt Stiel Blüte Grün").split(" ")));
list1.add(new Definition("Baum", ("Stamm Ast Blüte Grün Blatt").split(" ")));
list1.add(new Definition("Pilz", ("Hut Farbe Stiel").split(" ")));
list1.printAll();

var index1 = list1.index();
index1.printAll(); document.write("<hr>");

var list2 = new DefinitionList();
list2.add(new Definition("Tisch", ("Holz Beine").split(" ")));
list2.add(new Definition("Schrank", ("Holz Tür").split(" ")));
list2.add(new Definition("Stuhl", ("Lehne Beine Sitzfläche").split(" ")));
list2.add(new Definition("Bett", ("Holz Beine Laken").split(" ")));
list2.printAll();

var index2 = list2.index();
index2.printAll();                                         // lissalanda@gmx.at

                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

// NET 6.x | C# 10.x | VS-2022

var dicPlant = new Dictionary<string, List<string>>() {
    {"Blume", new List<string> { "Blatt", "Stiel", "Blüte", "Grün" } },
    {"Baum", new List<string> { "Blatt", "Ast", "Blüte", "Grün", "Stamm" } },
    {"Pilz", new List<string> { "Hut", "Farbe", "Stiel" } }
};

var dicFurniture = new Dictionary<string, List<string>>() {
    {"Tisch", new List<string> { "Holz", "Beine" } },
    {"Schrank", new List<string> { "Holz", "Tür" } },
    {"Stuhl", new List<string> { "Lehne", "Beine", "Sitzfläche" } },
    {"Bett", new List<string> { "Holz", "Beine", "Laken" } }
};

Dictionary<string, List<string>> Index(Dictionary<string, List<string>> defLst) =>
    defLst.SelectMany(x => x.Value).GroupBy(x => x).Select(x => x.Key)
    .Select(u => new { unique = u, lst = defLst.Where(d => d.Value.Contains(u))
    .Select(x => x.Key).ToList() }).ToDictionary(x => x.unique, x => x.lst);

void Print(Dictionary<string, List<string>> dic) => Index(dic).ToList().ForEach(x => Console.WriteLine($"{x.Key} - {string.Join(", ", x.Value)}"));

Print(dicPlant);
Print(dicFurniture);
                

Lösung von: Jens Kelm (@JKooP)

// C++ 14 | VS-2022
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using str = std::string;
using vstr = std::vector<str>;
using mstr = std::map<str, vstr>;

const mstr plants{
    {"Blume", {"Blatt", "Stiel", "Bluete", "Gruen"}},
    {"Baum", {"Stamm", "Ast", "Bluete", "Gruen", "Blatt"}},
    {"Pilz", {"Hut", "Farbe", "Stiel"}}
};

const mstr furniture{
    {"Tisch", {"Holz", "Beine"}},
    {"Schrank", {"Holz", "Tür"}},
    {"Stuhl", {"Lehne", "Beine", "Sitzfläche"}},
    {"Bett", {"Holz", "Beine", "Laken"}}
};

const auto get_results(const mstr& map_, const str& find_) {
    vstr result{ find_ };
    for (const auto& elem : map_)
        if (std::find(elem.second.begin(), elem.second.end(), find_) != elem.second.end())
            result.push_back(elem.first);
    return result;
}

const std::ostream& print(std::ostream& os_, const vstr& vec_) {
    if (vec_.size() < 2) return os_;
    std::cout << vec_[0] << ": ";
    for (auto it{ vec_.begin() + 1 }; it != vec_.end() - 1; ++it)
        std::cout << *it << ", ";
    std::cout << vec_.back() << "\n";
    return os_;
}

int main() {
    print(std::cout, get_results(plants, "Blatt") );
    print(std::cout, get_results(furniture, "Holz"));
}
                

Lösung von: Jens Kelm (@JKooP)

Verifikation/Checksumme:

Wenn Sie den so erzeugten Index wieder indexieren, sollte (abgesehen von der Rehenfolge der Begriffe) wieder die ursprüngliche Liste erscheinen.

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 2
Schwierigkeit: Mittel
Webcode: evjr-c0do
Autor: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen