0

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

  • It's not clear to me what you are trying to achieve. Do you need to flip all elements in the stack, e.g. from [blue, red, white] to [white, red, blue]? Or do you need to swap specific elements between each other, e.g. blue to red and green to yellow? – NikMashei Nov 17 '22 at 18:55
  • i need to do both, I have accomplished the flip portion eg the [red, white, blue] to [blue, white, red] portion. what needs to be done is to have a way to replace instances of a string with another string. So i need a general way to take "x" and replace it with "y" or even a scanner value. Basically i have to find a way to find instances of a string and change it with a string of my choosing – confusedcs Nov 17 '22 at 19:04
  • You have two things to do, a) flip the stack and b) flip the elements. Better to do them separately. Perhaps pop the first element from the original stack, flip it and push it onto the flipped stack. Repeat until the first stack is empty. – rossum Nov 17 '22 at 20:19

2 Answers2

0

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]
NikMashei
  • 371
  • 1
  • 7
  • 19
  • thank you for the link. I have already written a recursive method to flip a given stack. My issue is with trying to write a way to essential ctrl+f and then change an element in a general sense. So find all instances of "x" and then change it to "somethingElse" – confusedcs Nov 17 '22 at 19:07
  • Well, probably one of the simplest solutions would be to create a map like `Map map` containing values to replace in your stack. Let's consider you need to swap blue for red then you could init map with these values like: `map.put("blue", "red")`. You could easily iterate through the reversed stack and swap values using this map by finding a key in the map and getting a value associated with a key. – NikMashei Nov 17 '22 at 19:15
0

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]
pfurbacher
  • 1,789
  • 3
  • 15
  • 23