Home > Mobile >  flipping a stack and assigning new string variables
flipping a stack and assigning new string variables

Time:11-18

I'm a bit confused about what to do with this problem. I have to take a Stack and flip it, once flipped the elements in the stack have to also 'flip'. for example every string that reads 'blue' must now read 'red', every string that reads 'White' should be 'black' etc.

I've written a method to flip the stack, but writing a method to replace all instances of the given variables with new variables isn't working. This is what i have so far. I've tried two approaches and i'm still not getting the result i want. Here is what I have:

//here color is the name of my stack. I tried to convert the stack to an array 
        Object[] arr = color.toArray();

        for (int i =0;i<arr.length;i  ){ 
            /*
             * replace instances of "blue" in the string [] with red 
             */
            arr [i] = ((String) arr[i]).replaceAll("Blue", "Red");

            arr [i] = ((String) arr[i]).replaceAll("Red", "Blue");
            
            arr [i] = ((String) arr[i]).replaceAll("Green", "Yellow");
            
            arr [i] = ((String) arr[i]).replaceAll("Yellow", "Green");

            System.out.print(arr[i]);
        }

another method i tried:

import java.util.*;

public class colors{
    /*
     * method to swap the colors
     * color black gets changed to white, blue changes to red etc...
     * method would have to be implemented on a stack to change all the elm of the stack to the opposite 
     * then the stack gets printed out and can be changed in the flip part of the main method
     */

    private static Stack<String> opposite(Stack<String>color){ 
        // method takes stack of strings. if 'red' then change to 'blue'
        /*
         * the stack gets put into this method 
         * if the stack (strings) has these values then they are replaced with my values
         * 
         * can't return String values if the input is Stack<String>
         */

        String b = "blue";
        String r = "red";
        String g = "green";
        String y = "yellow";
       
            b.replace("blue", "red");
            r.replace("red", "blue");
            g.replace("green","yellow");
            y.replace("yellow","green");
        
         return color; // return type hase to be same as input type so change return type to match Stack<String>
         /*
          * if return type is same it can't return color.... 
          try using switch statement to 
          */
    }
    public static void main(String[]args){
        Stack<String> way = new Stack<>();
        color.push("red");
        color.push("blue");

        System.out.println(way);

        
        System.out.println(opposite(way)); 
    }
}

I wanted the method to intake a stack and output a stack that has the elements changed

CodePudding user response:

If you need to reverse all elements in a stack then you could find the solution here

upd: Probably this would be the solution for your problem. You could replace values in the map with needed for you, it contains rules "which color should be swapped to the another one"

public static void main(String[] args) {
    // initialize a map containing values to swap
    Map<String, String> map = new HashMap<>();
    map.put("red", "blue");
    map.put("white", "yellow");

    // let's say you got a stack like below
    Stack<String> stack = new Stack<>();
    stack.push("red");
    stack.push("white");

    System.out.println("Before the flip: "   stack);

    // iterate through the stack
    for (int i = 0; i < stack.size(); i  ) {
        var stackValue = stack.get(i);
        var flippedValue = map.get(stackValue);
        if (flippedValue != null) {
            stack.set(i, flippedValue);
        }
    }

    System.out.println("After the flip: "   stack);
}

the output of code below would be:

Before the flip: [red, white]
After the flip: [blue, yellow]

CodePudding user response:

Here's an approach which takes your opposites and

  1. creates a list of the pairs;
  2. provides a method to create a lookup map for efficient retrieval of the respective opposite;
  3. provides a method to flip both the order of the "stack" (using Deque, see in-line comments) and flip the color of each item in the queue.

This approach emphasizes the use of the Java Streams API for a more functional approach (i.e., avoid imperative for-loop iteration). See, Functional Programming with Java 8 by Venkat Subramaniam.

Hat-tip to: Java 8 stream reverse order, see the "Update 2016-01-29" note.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class OppositeColorsDeque {

    public static void main(String[] args) {
        // Assuming these are the only pairs of opposites...
        List<List<String>> colorOpposites = new ArrayList<>();
        colorOpposites.add(List.of("blue", "red"));
        colorOpposites.add(List.of("red", "blue"));
        colorOpposites.add(List.of("green", "yellow"));
        colorOpposites.add(List.of("yellow", "green"));

        System.out.println("colorOpposites list: "   colorOpposites);

        Map<String, String> oppositeColorLookup = createOppositeColorsLookupMap(colorOpposites);
        
        // Instead of a Stack, use Deque. See JavaDoc for Stack: 
        // "A more complete and consistent set of LIFO stack operations is 
        // provided by the Deque interface and its implementations, which 
        // should be used in preference to this class."
        Deque<String> originalDeque = new ArrayDeque<>();
        originalDeque.addAll(List.of("blue", "red", "green", "yellow"));

        System.out.println("deque1: "   originalDeque);

        Deque<String> flippedDeque = flip(originalDeque, oppositeColorLookup);

        System.out.println("deque2: "   flippedDeque);
    }

    protected static Map<String, String> createOppositeColorsLookupMap(List<List<String>> colorOpposites) {
        return colorOpposites.stream()
            .collect(Collectors.toMap(list -> list.get(0), list -> list.get(1)));
    }

    protected static Deque<String> flip(Deque<String> originalDeque, Map<String, String> oppositeColorsMap) {
        // See https://stackoverflow.com/a/24011264/1271785
        return originalDeque.stream()
            .map(element -> oppositeColorsMap.get(element))
            .collect(Collector.of(
                ArrayDeque::new,
                (deq, t) -> deq.addFirst(t),
                (d1, d2) -> { d2.addAll(d1); return d2; }));
    }

}

Output:

colorOpposites list: [[blue, red], [red, blue], [green, yellow], [yellow, green]]
deque1: [blue, red, green, yellow]
deque2: [green, yellow, blue, red]
  • Related