How to resolve the algorithm Variable declaration reset step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Variable declaration reset step by step in the Wren programming language

Table of Contents

Problem Statement

A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) If your programming language does not support block scope (eg assembly) it should be omitted from this task.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Variable declaration reset step by step in the Wren programming language

Source code in the wren programming language

var s = [1, 2, 2, 3, 4, 4, 5]

// There is no output as 'prev' is created anew each time
// around the loop and set implicitly to null.
for (i in 0...s.count) {
    var curr = s[i]
    var prev
    if (i > 0 && curr == prev) System.print(i)
    prev = curr
}

// Now 'prev' is created only once and reassigned
// each time around the loop producing the desired output.
var prev
for (i in 0...s.count) {
    var curr = s[i]
    if (i > 0 && curr == prev) System.print(i)
    prev = curr
}

  

You may also check:How to resolve the algorithm Statistics/Basic step by step in the Ring programming language
You may also check:How to resolve the algorithm Mouse position step by step in the xTalk programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the TI-89 BASIC programming language
You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the Oforth programming language
You may also check:How to resolve the algorithm McNuggets problem step by step in the 8080 Assembly programming language