How to resolve the algorithm Stem-and-leaf plot step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Stem-and-leaf plot step by step in the Java programming language

Table of Contents

Problem Statement

Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.

Note: If you wish to try multiple data sets, you might try this generator.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Stem-and-leaf plot step by step in the Java programming language

Explanation of the Java Code:

The provided Java code implements a program that creates a stem-and-leaf plot, a simple graphical representation of a frequency distribution. It's commonly used to visualize data and identify patterns.

The code has two main parts:

1. StemAndLeaf Class (Traditional Implementation):

  • createPlot Method:

    • Takes an array of integers (int... data) representing the values to be plotted.
    • Creates a TreeMap to store the plot, where stems are keys and leaves are values.
    • Iterates over the data and calculates the stem (integer division by 10) and leaf (modulus by 10) for each value.
    • Adds the leaf to the corresponding stem in the plot.
    • Ensures that all stems from 0 to the highest stem value have an entry in the plot, even if they don't have any leaves.
  • printPlot Method:

    • Prints the stem-and-leaf plot by iterating over the entries in the plot.
    • Sorts the leaves for each stem and prints them in a tabular format.

2. StemAndLeaf Interface (Stream-Based Implementation):

  • createPlot Method:

    • Similar to the traditional implementation, but uses Java 8 streams and collectors.
    • Creates a Map grouped by stem using Collectors.groupingBy.
    • Maps each value to its leaf using Collectors.mapping.
  • printPlot Method:

    • Streams over the entries in the plot and sorts the leaves.
    • Uses String.join to concatenate the stem, separator, and leaf list into a formatted string.
    • Prints the formatted strings.

Main Function:

  • Initializes an array data with the values to be plotted.
  • Calls the createPlot and printPlot methods from either the StemAndLeaf class or the StemAndLeaf interface to generate and print the stem-and-leaf plot.

How it Works:

The code generates a stem-and-leaf plot from the given data by grouping the values into stems and leaves, where the stem represents the tens digit and the leaf represents the units digit. The resulting plot provides a visual representation of the frequency distribution of the data, allowing users to quickly identify patterns and outliers.

Benefits of Using Streams:

The stream-based implementation demonstrates how Java 8 streams can simplify and enhance the code:

  • It eliminates the need for explicit loops and manual sorting.
  • It leverages parallel processing, improving performance for larger datasets.
  • It provides a concise and declarative syntax, making the code more readable and maintainable.

Source code in the java programming language

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class StemAndLeaf {
	private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118,
			44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105,
			132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63,
			27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113,
			121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27,
			43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118,
			117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122,
			109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34,
			133, 45, 120, 30, 127, 31, 116, 146 };
	
	public static Map<Integer, List<Integer>> createPlot(int... data){
		Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>();
		int highestStem = -1; //for filling in stems with no leaves
		for(int datum:data){
			int leaf = datum % 10;
			int stem = datum / 10; //integer division
			if(stem > highestStem){
				highestStem = stem;
			}
			if(plot.containsKey(stem)){
				plot.get(stem).add(leaf);
			}else{
				LinkedList<Integer> list = new LinkedList<Integer>();
				list.add(leaf);
				plot.put(stem, list);
			}
		}
		if(plot.keySet().size() < highestStem + 1 /*highest stem value and 0*/ ){
			for(int i = 0; i <= highestStem; i++){
				if(!plot.containsKey(i)){
					LinkedList<Integer> list = new LinkedList<Integer>();
					plot.put(i, list);
				}
			}
		}
		return plot;
	}
	
	public static void printPlot(Map<Integer, List<Integer>> plot){
		for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){
			Collections.sort(line.getValue());
			System.out.println(line.getKey() + " | " + line.getValue());
		}
	}
	
	public static void main(String[] args){
		Map<Integer, List<Integer>> plot = createPlot(data);
		printPlot(plot);
	}
}

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public interface StemAndLeaf {
  public static final int[] data = {12, 127, 28, 42, 39, 113, 42, 18, 44, 118,
    44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105,
    132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63,
    27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113,
    121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27,
    43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118,
    117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122,
    109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34,
    133, 45, 120, 30, 127, 31, 116, 146};

  public static Map<Integer, List<Integer>> createPlot(int... data) {
    Map<Integer, List<Integer>> plot = Arrays.stream(data)
      .parallel()
      .boxed()
      .collect(
        Collectors.groupingBy(
          datum -> datum / 10, // stem, integer division
          Collectors.mapping(
            datum -> datum % 10, // leaf
            Collectors.toList()
          )
        )
      )
    ;
    int highestStem = Arrays.stream(data)
      .parallel()
      .map(datum -> datum / 10)
      .max()
      .orElse(-1) //for filling in stems with no leaves
    ;
    Optional.of(plot)
      .map(Map::keySet)
      .map(Collection::size)
      .filter(size -> size < highestStem + 1 /*highest stem value and 0*/)
      .ifPresent(p ->
        IntStream.rangeClosed(
          0,
          highestStem
        )
          .parallel()
          .forEach(i ->
            plot.computeIfAbsent(i, $ -> new LinkedList<>())
          )
      )
    ;
    return plot;
  }

  public static void printPlot(Map<Integer, List<Integer>> plot) {
    plot.entrySet()
      .stream()
      .parallel()
      .peek(line -> Optional.of(line)
        .map(Map.Entry::getValue)
        .ifPresent(Collections::sort)
      )
      .map(line ->
        String.join(" ",
          String.valueOf(line.getKey()),
          "|",
          String.valueOf(line.getValue())
        )
      )
      .forEachOrdered(System.out::println)
    ;
  }

  public static void main(String... arguments) {
    Optional.of(data)
      .map(StemAndLeaf::createPlot)
      .ifPresent(StemAndLeaf::printPlot)
    ;
  }
}

  

You may also check:How to resolve the algorithm Zhang-Suen thinning algorithm step by step in the Wren programming language
You may also check:How to resolve the algorithm Execute Brain step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Ramer-Douglas-Peucker line simplification step by step in the Julia programming language
You may also check:How to resolve the algorithm SHA-1 step by step in the Halon programming language
You may also check:How to resolve the algorithm Best shuffle step by step in the Erlang programming language