PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

Friday, November 4, 2022

[FIXED] How to cast lambda parameter to char in the ifPresentOrElse() method

 November 04, 2022     for-loop, java, java-stream, lambda, stack     No comments   

Issue

How do I fix this code block (in ifPresentOrElse())?

I'm stuck here with:

Inconvertible types; cannot cast '<lambda parameter>' to 'char'

Please advise how to get this compiled and running.

public static boolean isBracketsInOrder1(String bracket) {
    
    Stack<Character> charStack = new Stack<>();
    static Map<Character, Character> leftToRightBracketsMap = 
                                       Map.of('{', '}', '[', ']', '(', ')');
    bracket.chars()
        .filter(i -> leftToRightBracketsMap.containsKey((char) i))
        .findFirst()
        .ifPresentOrElse((i) -> charStack.push((char) i),
            (i) -> {
                // code does not COMPILE at equals((char) i)
                return leftToRightBracketsMap.get(charStack.pop()).equals((char) i);
            });
    return true;
}

And this is the working code using for loop representing what I'm trying to implement above using streams above.

public static boolean isBracketsInOrder(String bracket) {
    Stack<Character> charStack = new Stack<>();
    static Map<Character, Character> leftToRightBracketsMap = 
                                       Map.of('{', '}', '[', ']', '(', ')');
    boolean matchFound = true;
    for (char c : bracket.toCharArray()) {
        if (leftToRightBracketsMap.containsKey(c)) charStack.push(c);
        else {
            char leftBrack = charStack.pop();
            char correctBrack = leftToRightBracketsMap.get(leftBrack);
            if (c != correctBrack) return false;
        }
    }
    return true;
}

Solution

You've introduced the code for a very basic algorithmic question - validate a string of brackets.

There are many mistakes in your code:

  • A stream doesn't act precisely like a loop, when it hits the terminal operation (which is findFirst() in your code), it's done. Code inside ifPresentOrElse() would not be executed multiple times (you probably expected the opposite). It would be invoked only once on an optional result returned by the findFirst().

  • As its second argument ifPresentOrElse() expects an instance of the Runnable interface. Method run() neither expects any arguments, no returns a value. Therefore, this attempt to define a Runnable is incorrect: (i) -> { return something; }.

  • Any lambda expressions should to conform to a particular functional interface (see). It can't appear out of nowhere.

  • Class Stack is legacy, it's still in the JDK for backward compatibility reasons. Implementations of the Deque interface should be used instead.

  • You are not checking whether the stack is empty, which can cause an EmptyStackException. If you would replace the Stack with ArrayDeque the problem will remain, method pop() will throw NoSuchElementException. You need to make sure that stack is not empty.

  • Returning true in the imperative solution is not correct. Instead, you need to return charStack.isEmpty(), because if there are some elements in the stack - sequence is not valid, there are brackets that haven't been closed.

Implementing this problem using streams requires far more efforts than a solution using a plain loop.

According to the documentation, the only place where mutation can occur in a stream is inside the collector. As a general rule, all functions used in a stream pipeline should not operate via side effects and accumulate the stated outside the stream (apart from some edge cases, see the link). Only collector's mutable container should maintain a state.

We can contract such a collector using Collecor.of() method:

public static boolean isValidBracketSequence(String brackets) {
    return brackets.chars()
        .mapToObj(c -> (char) c)
        .collect(getBracketCollector());
}

public static Collector<Character, ?, Boolean> getBracketCollector() {
    
    return Collector.of(
        BracketContainer::new,
        BracketContainer::add,
        (left, right) -> { throw new AssertionError("should not be executed in parallel"); },
        bracketContainer -> bracketContainer.isValid() && bracketContainer.isEmpty()
    );
}

That's how a mutable container might look like:

class BracketContainer {
    public static final Map<Character, Character> leftToRightBracketsMap =
        Map.of('(', ')', '[', ']', '{', '}');
    
    private Deque<Character> stack = new ArrayDeque<>();
    private boolean isValid = true;
    
    public void add(Character next) {
        if (!isValid) return;
        
        if (leftToRightBracketsMap.containsKey(next)) {
            stack.push(next);
        } else {
            compare(next);
        }
    }
    
    public void compare(Character next) {
        
        this.isValid = !isEmpty() && leftToRightBracketsMap.get(stack.pop()).equals(next);
    }
    
    public boolean isEmpty() {
        return stack.isEmpty();
    }
    
    public boolean isValid() {
        return isValid;
    }
}

main()

public static void main(String[] args) {
    System.out.println("(([])) -> " + isValidBracketSequence("(([]))")); // true
    System.out.println("(([]]) -> " + isValidBracketSequence("(([]])")); // false
    System.out.println("(([})) -> " + isValidBracketSequence("(([}))")); // false
    System.out.println("({[])) -> " + isValidBracketSequence("({[]))")); // false
    System.out.println("({[]}) -> " + isValidBracketSequence("({[]})")); // true
}

Output:

(([])) -> true
(([]]) -> false
(([})) -> false
({[])) -> false
({[]}) -> true

A link to Online Demo



Answered By - Alexander Ivanchenko
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] How can I print the last item in the stack? (using dart)

 November 02, 2022     dart, flutter, indexing, stack     No comments   

Issue

class CustomStack<T> {
  final _list = <T>[];
  void push(T value) => _list.add(value);
  T pop() => _list.removeLast();
  T get top => _list.last;
  bool get isEmpty => _list.isEmpty;
  bool get isNotEmpty => _list.isNotEmpty;
  int get length => _list.length;
  @override
  String toString() => _list.toString();
}

void main() {
  CustomStack<String> plates = CustomStack();
//Add plates into the stack
  plates.push("Plate1");
  plates.push("Plate2");
  plates.push("Plate3");
  plates.push("Plate Extra");
  print(plates);
  print(plates[plates.length-1]);
}



I get an error in the last line "The operator '[]' isn't defined for the type 'CustomStack'." How can I control the index in the stack. I want to print only "Plate Extra" on the screen.


Solution

There is no need to use that structure plates[plates.length-1] if getting the last element is possible with the built function. If you want to get the last item in Custom Stack, you can define a function in your Custom Stack.

T get peek => _list.last;



Answered By - Nijat Namazzade
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 28, 2022

[FIXED] How to check if a Stack<T> is empty

 October 28, 2022     c#, is-empty, stack     No comments   

Issue

Is there some other way, except Stack<T>.Count() == 0, to check if a Stack<T> is empty?

Coming from C++/Java background where "stack" classes generally have some sort of dedicated "is empty" method like Java - Stack.empty.


Solution

Instead of using .Count() == 0, just use .Count == 0. This is using the stack's property rather than the linq extension method.



Answered By - recursive
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check if the stack is empty in MIPS?

 October 28, 2022     is-empty, mips, stack     No comments   

Issue

So I need to check if the stack is empty before returning a value that is being calculated. if its not empty, then I will raise an error.

How can I check if the stack is empty or not? Compare $sp with null, how? or if starting address of $sp is always the same, should I hard code it? (if address of $sp equal to 270346..3, then empty) (this feels very wrong)

Any help would be appreciated Thanks


Solution

You should never check if the call stack is "empty" — this concept doesn't really make sense — the call stack is supposed to always be there.


However, if you are pushing a dynamic number of things onto the stack, and later popping them all of them off, you can either:

  • Capture the value of stack pointer before any of the dynamic pushing, and then as part of dynamic popping compare the current stack pointer with that previously captured stack pointer — when they are equal, there's nothing to pop.

  • Alternately, start a count at zero before any dynamic pushing, and add to that count as items are pushed, decrement the count as they are popped — whenever the count is zero, then there's nothing to pop.


On the other hand, if you are writing a program that takes control directly from the simulator or from the operating system, these are special in that there is no one to return to.  Because of this, usually we use custom startup code for that, and such startup code is not a classic function.

Any code that is written as a function can assume that it was called, and thus can return to its caller.



Answered By - Erik Eidt
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 8, 2022

[FIXED] Why can I not get worldclim data (avg temp and prec) for the state which I live at all using R?

 October 08, 2022     r, spatial, stack, statistics     No comments   

Issue

I'd like to get the average temperature and precipitation for the state of Ceara in Brazil; I made a cropped area on the map as:

enter image description here

and I used the center lat/lon as lat=-5.49839 and lon=-39.32062 I got the caps of latitude and longitude as latinicial=-7.24614 (minimum latitude), latfinal=-3.76140 (maximum latitude), longinicial=-40.38084 (minimum longitude) and longfinal=-38.77385 (maximum longitude) then I've simulated a uniformly distributed temperature for both latitude and longitude which lies in their maxima and minima.

My code is given as follows:

library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(dismo)
library(rgdal)
library(sf)
d=getData('worldclim',lat=-5.49839,lon=-39.32062,res=0.5,var='bio')
latinicial=-7.24614
latfinal=-3.76140
longinicial=-40.38084
longfinal=-38.77385
latitude=runif(100,latinicial,latfinal)
longitude=runif(100,longinicial,longfinal)
coord=data.frame(latitude,longitude)
points = SpatialPoints(coord, proj4string = d@crs)
d <- d[[c(1,12)]]
names(d)=c("Temp","Prec")
extract(d,points)

But when I run it, I got NA values for all rows even though I'm showing you only 4 rows:

enter image description here

So, I'd like to know what happened to it. Why do I get NA values?


Solution

The problem is with the order of longitude and latitude in coords. When you put coords into SpatialPoints, it expects the order to be longitude then latitude, but you have it reversed. Once you fix that, then it will extract the data correctly. All the code above coord works fine. Also, if you are going to run this code multiple times, then I would recommend using set.seed. This will allow you to get the same values every time when you run the runif statements.

library(raster)
library(sp)

set.seed(243)
d = getData(
  'worldclim',
  lat = -5.49839,
  lon = -39.32062,
  res = 0.5,
  var = 'bio'
)
latinicial = -7.24614
latfinal = -3.76140
longinicial = -40.38084
longfinal = -38.77385
latitude = runif(100, latinicial, latfinal)
longitude = runif(100, longinicial, longfinal)
coord = data.frame(longitude, latitude)
points = SpatialPoints(coord, proj4string = d@crs)
d <- d[[c(1, 12)]]
names(d) = c("Temp", "Prec")
extract(d, coord)

Output

head()

       Temp Prec
  [1,]  239  655
  [2,]  267  832
  [3,]  256  541
  [4,]  269  740
  [5,]  242  784
  [6,]  233  981


Answered By - AndrewGB
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 14, 2022

[FIXED] How to output direction of shortest path?

 August 14, 2022     algorithm, breadth-first-search, java, output, stack     No comments   

Issue

This is a simple maze solver program.

.0........
..........
.0...0.0.0
...0...0..
..........
.0.0......
.........0
...F....0.
..........
S.0...0...

this is the simple maze i'm working on. I implemented a solution to output cordinates of the path as follow.(cordinates aquired from a BFS algorithm)

Start - x = 9 y = 0
Move up to - x = 8 y = 0
Move up to - x = 7 y = 0
Move Right to - x = 7 y = 1
Move Right to - x = 7 y = 2
Move Right to - x = 7 y = 3
Finish

but I want to output like below(omit same direction and only output direction and last coordinate to same direction),

Start        - x = 9 y = 0
Move up to   - x = 7 y = 0
Move Right to- x = 7 y = 3
Finish

this all coordinates are allocated to a stack.below is my code,

System.out.println("Start - " + curr);
        curr = stack.pop();


        while (!stack.isEmpty()) {
            System.out.println(curr);
            curr = stack.pop();
        }
        System.out.println(curr);

    }

Solution

The simplest way is to define a function that takes two coordinates, and returns the direction, then iterate through the coordinates and check if there is a change compared to the next one.

public static String getDirection(int x1, int y1, int x2, int y2) {
    if(x1 == x2 && y1 > y2)
        return "up";
    if(x1 == x2 && y1 < y2)
        return "down";
    if(y1 == y2 && x1 < x2)
        return "right";
    if(y1 == y2 && x1 > x2)
        return "left";
    return "undecidable";
}

// It is written so just for simplicity. 
// Use an array of Coord structs or something like that.
public static void printDirections(int[] x, int[] y) {
    System.out.printf("Start - x = %d y = %d\n", x[0], y[0]);

    String lastDirection = getDirection(x[0], y[0], x[1], y[1]);
    for(int i = 1; i < x.length - 1; i++) {
        String direction = getDirection(x[i], y[i], x[i + 1], y[i + 1]);
        if(!lastDirection.equals(direction)) {
            System.out.printf("Move %s to x = %d y = %d", lastDirection, x[i], y[i]);
        }

        lastDirection = direction;
    }
    System.out.printf("Move %s to x = %d y = %d", lastDirection, x[x.length - 1], y[y.length - 1]);
}


Answered By - tvili999
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] Why is my python code to convert an number to binary using stack not working?

 August 10, 2022     binary, decimal, python-3.x, stack     No comments   

Issue

The following is my code to convert a number to binary using stacks written in Python3. Whenever I run it, None is produced as the output. What might be causing this? Thanks in advance.

class Stack():
    def __init__(self):
        self.stack = []
        self.top = -1

def push(self, val):
    self.stack.append(val)
    self.top += 1

def pop(self):
    if self.top == -1:
        print('Underflow')
    else:
        del self.stack[self.top]
        self.top -= 1

def empty(self):
    return self.stack == []

def peek(self):
    return self.top

def display(self):
    return self.stack

def binary(n):
    b = Stack()
    while n > 0:
        r = n%2
        b.push(r)
        n = n//2

    bn = ''
    while not b.empty():
        bn += str(b.pop())

    return bn

print(binary(242))

Solution

This line just pops the elements from the stack and does not return anything.It returns None.

bn += str(b.pop()) 

You must store the top element in a variable and then pop the stack after it.

Try this below in your binary function :

def binary(n):
    b = Stack()
    while n > 0:
        r = n % 2
        b.push(r)
        n = n//2
    print(b.stack)
    bn = ''
    while not b.empty():
        bn += str(b.stack[-1])
        b.pop()
    return bn


Answered By - Abhishek Kulkarni
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] Where is the super reference in a Java instance method's stack frame?

 July 10, 2022     java, jvm, reference, stack, super     No comments   

Issue

I read Bill Venner's excellent Inside the Java Virtual Machine book, which, in Chapter 5 explores in detail, among other things, the composition of a JVM's stack frame. (This chapter from the book also happens to be officially published here: https://www.artima.com/insidejvm/ed2/jvm8.html) Apart from this book I studied relatively much the runtime data areas of some JVM's, especially their stack and heap.

In an instance method's stack frame, the local variables section constitutes an array of words which holds the method arguments (or parameters), local variables and the "hidden" this reference.

What I'd like to know is, where is the super reference stored, as that is also always available in any non-static context (i.e. instance method body or initializer block), except in the Object class. Is it stored somewhere alongside the reference "this"? If yes, then why is it seemingly always left out from stack frame representations/overviews?


Solution

There is no "super" reference.

When you do:

super.foo()

You "seem" to be calling foo on an object called "super", but that's merely Java's syntax, and doesn't have to reflect what's happening under the hood. When this call is translated, it is translated to a invokespecial instruction, that invokes the superclass's foo method.

Compare this to a this.foo() call, which translates to a invokevirtual instruction. Unlike invokespecial, this will do dynamic dispatch, selecting the right method to call, depending on the runtime type of this.

Note that in both cases, there is a aload_0 instruction before invoking the method, loading the this reference onto the stack.



Answered By - Sweeper
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 6, 2022

[FIXED] How to update pointers when pushed on to std::stack using iteration?

 July 06, 2022     binary-tree, c++, iteration, pass-by-reference, stack     No comments   

Issue

Here is the situation:

Given a pointer to the root of a binary search tree(of integers) root and an integer data, perform the rotate function (predefined) on all the ancestral nodes of the node containing data using iterative method. For simplicity, assume data exists and always occurs on the leaf nodes.

The rotate function passes the pointer by reference as follows:

struct Node
{
    Node *left;
    int data;
    Node *right;
};

void rotate(Node* &root); // performs some rotation on the root and reflects the change.

void search(Node* &root, int data)
{
    stack<Node*> s;
    while(root->data!=data)
    {
        s.push(root);
        if(data<root->data)
            root=root->left;
        else
            root=root->right;
    }

    while(!s.empty())
    {
        rotate(s.top()); // does not reflect changes to root
        s.pop();
    }
}

The iterative version requires the use of a stack. std::stack::push() function pushes the pointer by value. As a result, while popping the ancestral pointers, I would be reflecting changes in the stack instead.

What is the best work around for this situation?


Solution

This solves my problem.

void search(Node* &root, int data)
{   
    if(root->data==data)
        return;

    stack<Node**> s;
    while(root->data!=data)
    {
        if(data<root->data)
        {
            s.push(&root->left);
            root=root->left;
        }
        else
        {
            s.push(&root->right);
            root=root->right;
        }
    }
    s.pop(); // to avoid leaf
    while(!s.empty())
    {
        rotate(*s.top())
        s.pop();
    }
    rotate(root);
}


Answered By - DoubtExpert
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 5, 2022

[FIXED] Why do I have to return a pointer when i'm working with dynamic data type? (i.e stack, list, queue, dynamic array)

 July 05, 2022     c, pass-by-reference, pointers, stack     No comments   

Issue

When using pop and push function, I have to return a pointer otherwise the variable stack doesn't change. Does anyone know why?

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

//Defining stack element
typedef struct element
{
    int num;              //Content of the element
    struct element *next; //Pointer to the next element
}element;

element *push(element *s, int x); //Insert x elements in the stack
void print(element *s);           //Prints the stack's elements
element *pop(element *s);         //Removes the stack's top element

int main()
{
    element *stack = NULL; //Pointer to the stack's top element
    int x;

    printf("Insert the number of elements: ");
    scanf("%d", &x);

    stack = push(stack, x);
    print(stack);

    stack = pop(stack);
    print(stack);

    return 0;
}

element *push(element *s, int x)
{
    element *newElement;

    for(; x > 0; x--)
    {
        newElement = (element*)malloc(sizeof(element));

        printf("Number: ");
        scanf("%d", &newElement->num);

        newElement->next = s;
        s = newElement;
    }

    return s;
}

void print(element *s)
{
    element *through = s;

    printf("Your stack:\n");

    while(through != NULL)
    {
        printf("%d\t", through->num);
        through = through->next;
    }
    printf("\n");
}

element *pop(element *s)
{
    element *elementDeleted = s;
    s = elementDeleted->next;

    printf("Element deleted: %d\n", elementDeleted->num);

    free(elementDeleted);
    elementDeleted = NULL;

    return s;
}

I simply expected to modify the pointer stack in the functions, so I expected the functions to be void. But actually if I don't return the pointer the stack variable keeps its starting value (in this case NULL).


Solution

You need to usse a double pointer in your function arguments:

// Add a new value to the top of the stack
void push(element **s, const int x);
// Print the stack
void print(const element *s);
// Try removing the top element of the stack and returning it
int pop(element **s);

You then call push and pop with a reference to the stack pointer:

push(&stack, x);
pop(&stack);

Then, if you want to modify the pointer to the stack, you dereference s once: *s = newElement, but if you want to get the value of the top element, you dereference it twice: const int num = (*s)->num;.

The reason for needing to do this is that when you pass a pointer to the stack to a function, that function receives a copy of the pointer. This new pointer refers to the same stack, so modifying the values in the stack will work, but modifying the pointer itself will do nothing outside the function.

If instead you use a pointer to the pointer to your stack, then you allow that second pointer to be modified, because only the top-level pointer is a copy.



Answered By - Billy Brown
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing