Does Pseudocode execute single return statement and skip other return statements? - pseudocode

The LS algorithm that I found on internet:
LINEARSEARCH(A, v)
for i=0 to A.length-1
if(A[i] == v)
return i
return NIL
My question is : won’t it return NIL after exiting for loop? Do pseudocode execute a single return statement ?
Thanks in advance for the responses.

Related

Golang := operator for multiple variables [duplicate]

This question already has answers here:
Assigning slice vs redeclaring slice in Go
(3 answers)
Multi-variable short redeclaration when inside a for loop creates a new variable?
(2 answers)
Closed 9 months ago.
I'm starting using Golang as my main programming language to do exercises in LeetCode, and I get a strange result for Golang's := operator for multiple variables.
Let me say the question 104 to get the maxDepth of a binary tree.
My first solution is to use layer traversing, and below is my code.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
var s []*TreeNode
var cur *TreeNode
depth := 0
s = append(s, root)
for len(s) != 0 {
size := len(s)
depth++
for i := size; i > 0; i-- {
s, cur = s[1:], s[0]
if cur.Left != nil {
s = append(s, cur.Left)
}
if cur.Right != nil {
s = append(s, cur.Right)
}
}
}
return depth
}
The upper code snippet can pass the test. But the below code snippet can't, and I don't know why, I just can debug the for loop can't finish, and it becomes an infinite loop.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
var s []*TreeNode
depth := 0
s = append(s, root)
for len(s) != 0 {
size := len(s)
depth++
for i := size; i > 0; i-- {
s, cur := s[1:], s[0]
if cur.Left != nil {
s = append(s, cur.Left)
}
if cur.Right != nil {
s = append(s, cur.Right)
}
}
}
return depth
}
I hope anyone can explain to me how Golang handles the := operators for multiple variables and at least one of which has already been declared in some other place. Also, you can put some official links which can prove your explanation.
If any new variable is on the left of := (which is required by the compiler) then all variables are redefined. This shadows previous variables in previous scopes.
In the second code sample, you create a new s and append to it, but the s defined before the for was not modified.
The assignment operator := isn't that big of a villain as you think it is. The actual culprit in you code is the scope of variable s.
In the first code snippet, the var s is defined outside the first (outer) for-loop. Inside inner for-loop it was only assigned.
var s []*TreeNode // Definition
s, cur = s[1:], s[0] // Assignment
Whereas in second code snippet, both statements are defining the same variable. In other words, the second assignment is creating a different var s whose scope is limited to second (inner) for-loop.
var s []*TreeNode // Definition
s, cur = s[1:], s[0] // Definition + Assignment
"So why does this cause a difference?", is the question. I've added example data and printing logic to your code snippets in Playground. Check by running them both.
1st Snippet
2nd Snippet
If you see outputs of both, the first logic (with only 1 definition) gives the expected output. But second logic (2 definitions) goes into an infinite loop. This is because the scope of the second s which got defined inside the for-loop starts after the second definition and ends with iteration of the same for-loop.
For understanding, let's call the s defined above for-loop as s_outer and the s defined inside for-loop as s_inner. Logically both should mean the same thing, but due to difference in scope, they act as follows:
for i := size; i > 0; i-- {
s_inner, cur := s_outer[1:], s_outer[0]
if cur.Left != nil {
s_inner = append(s_inner, cur.Left)
}
if cur.Right != nil {
s_inner = append(s_inner, cur.Right)
}
}
Since assignment statement is executed right-to-left, first the compiler checks for s at s[1:], s[0]. Since s_inner is yet to be defined, it will consider s to be s_outer. When it assigns, i.e., control is now on the left side of = sign in s, cur := s[1:], s[0], since it is a new definition as per := usage in Go, it takes new variable s_inner. But the scope of s_inner ends after the current iteration. i.e., after if cur.Right != nil {...}. And so, from 2nd iteration, the s value is taken as s_outer again and assigned to s_inner. This gets repeated, and hence, infinite loop!!
Baseline: If a variable is defined with the same name as an existing
variable but in an inner scope, it acts like a different variable
altogether.
I doubt these concepts cannot be efficiently explained using description. Moreover, this is more of a use-case than property of the := operator. So, the godoc and other pages must've explained it as definition+assignment. You face an issue, you research and you learn. That's the only mantra for these concepts.

What the meaning of the ~once~ variable in the following code snippet?

The question is about the usage once variable in the following snippet extracted from the pipe.go of the standard go library
for once := true; once || len(b) > 0; once = false {
select {
case p.wrCh <- b:
nw := <-p.rdCh
b = b[nw:]
n += nw
case <-p.done:
return n, p.writeCloseError()
}
}
My understanding is that, the loop won't terminate as long as len(b) > 0 and the loop would be executed at least once.
So why not just write
for len(b) > 0 { ... }
It looks like once is being used to make a do ... while(condition); loop, which Go does not have.

Algorithm: Understanding recursive function

I'm learning Golang and i'm trying to understand the logic behind the output of a recursive function.
Here is my program :
package main
import(
"fmt"
)
func rec(i int) (int){
if i == 5{
fmt.Println("Break", i)
return i
}
rec(i+1)
fmt.Println("i = ", i)
return i
}
func main(){
j := 0
j = rec(1)
fmt.Println("Value j = ", j)
}
The output:
Break 5
i = 4
i = 3
i = 2
i = 1
Value j = 1
My questions are:
Why the first output (break 5) is in the top of outputs? Isn't the last output in my function to be printed ?
And why in the main function
j = rec(1)
return 1 and ignore the return of the condition ?
if i == 5{
fmt.Println("Break", i)
return i // Here normally the return will be: return 5 ??
}
PS: I'm using Go version go1.2.1 linux/386 under Ubuntu 14.04
Thanks for your answers.
This line in the func rec(i int) function
rec(i+1) // recurse at the i+1 value
fmt.Println("i = ", i)
Recursively iterates i until it reaches 5, after which your if condition triggers, which is why 5 is first printed, and then it successively goes down through the call stack, printing 4, then 3, ... etc.
This is a question r.e. recursion, not Go specifically. There are numerous resources to help you understand, here is an explanation of recursion in the Towers of Hanoi problem.

Why am I getting an never ending loop when reading from a byte.Buffer

Currently I'm writing a program that is reading a buffer from bytes.Buffer. Its supposed to stop reading when it finds the character e. But when I was reading the buffer using a for loop I noticed something odd. When I put the byte reading as part of the for statement I get an infinity loop (example in go playground):
b := bytes.NewBuffer([]byte("uoiea"))
for v, _ := b.ReadByte(); v != 'e'; {
println("The value is " + string(v))
}
But if I removed it and put it inside the for loop, it doesn't (example in go playground):
b := bytes.NewBuffer([]byte("uoiea"))
for ;; {
v, _ := b.ReadByte()
println("The value is " + string(v))
if v == 'e'{
break
}
}
Does anyone know why is this? I find it that adding the break expression is a very ugly and error prone way to solve this.
Because your post statement of the for-loop is empty (you have only init statement), so you don't read next byte every iteration (v is always 'u').
Here is the fixed version:
b := bytes.NewBuffer([]byte("uoiea"))
for v, _ := b.ReadByte(); v != 'e'; v, _ = b.ReadByte() {
println("The value is " + string(v))
}
As mentioned in comments, it's also recommended to check the error to avoid infinite loop when there is no 'e' byte:
b := bytes.NewBuffer([]byte("uoiea"))
for v, e := b.ReadByte(); v != 'e' && e == nil; v, e = b.ReadByte() {
println("The value is " + string(v))
}
ReadBytes returns io.EOF error when buffer is empty.
You are only reading the buffer once, when you are entering the loop. So the value of v will always be 'u'. You could solve it by reading the next byte in for loop's post statement also:
for v, _ := b.ReadByte(); v != 'e'; v, _ = b.ReadByte() {
// This works as long as there is an 'e' in your buffer
// Otherwise this goes to infinite loop also, as you are discarding error
But your second example is actually better and less ugly way to do this. There's nothing wrong with using break in loops like this. Actually it's very idiomatic in Go to write Read() loops as conditionless for loops and break from the loop when appropriate (usually when you get an io.EOF error indicating you reached the end of whatever you are reading). It leads to code that is easier to read, especially when there are many conditions that should cause break. The idiomatic and preferred (IMHO) way to write the code would be this:
b := bytes.NewBuffer([]byte("uoiea"))
for {
v, err := b.ReadByte()
if err == io.EOF {
// End of buffer. Should always break here to avoid infinite loop.
break
}
if err != nil {
// Error other than io.EOF means something went wrong with reading.
// Should handle it appropriately. Here I'll just panic.
panic(err)
}
if v == 'e' {
break
}
println("The value is " + string(v))
}
Which is almost the same as your working example. Just with error checks. But the io.EOF error check especially is very important, otherwise you''ll be stuck in infinite loop if there is no 'e' in your buffer.

Check if all items in a slice are equal

I need to create a function that:
returns true if all elements in a slice are equal (they will all be the same type)
returns false if any elements in a slice are different
The only way I can think of doing it is to reverse the slice, and compare the slice and the reversed slice.
Is there a better way to do this thats good syntax and more efficient?
I am not sure what your though process was for reversing the slice was, but that would be unnecessary. The simplest algorithm would be to check to see if all elements after the the first are equal to the first:
func allSameStrings(a []string) bool {
for i := 1; i < len(a); i++ {
if a[i] != a[0] {
return false
}
}
return true
}
Although there is an accepted answer, I'm just posting it with range keyword.
func allSameStrings(a []string) bool {
for i, v := range(a) {
if v != a[0] {
return false
}
}
return true
}

Resources