If JavaScript is dynamic scoping, what would be the last console.log() result in the following code? - scoping

This is how I defined the functions and the variable x,y,z is defined with some integer.
var a = 0;
var x = 1;
var y = 2;
var z = 3;
function f(n) {
a = n;
}
function g(){
console.log(a);
}
function h(){
f(x); g();
}
function k() {
var a = 0; g(); f(y);
}
f(z); g(); k(); g(); h(); g();
The following is my thoughts on if the code above is dynamically scope:
f(z){
a = z; // The value of a became z
}
g(){
console.log(a); // Printing out the value of z
}
k(){
var a = 0;
g(){
console.log(a); // Printing out 0
}
f(y){
a = y; // Assign the value of y to the variable a initialized 5 lines above
}
}
g(){
console.log(a); // Printing out the value of z
}
h(){
f(x){
a = x;
}
g(){
console.log(a) // Printing out the value of x
}
}
g(){
console.log(a) // Printing out value of z or x ??
}
Not sure what the last console.log will output.

See the example snippet with it's comments:
var a = 0;
var z = 1;
var x = 2;
var y = 4;
function f(n) {
a = n;
}
function g(){
console.log(`value of var a is ${a}`); // output var a value to console
}
function h(){
f(x); // a becomes 2 here since x = 2
g(); // output var a value to console
}
function k() {
var a = 0; // this sets a to 0 only in function scope
console.log(`function scope value of var a is ${a}`);
g(); // output var a value to console which is 1 here not 0
f(y); // a becomes 4 here since y = 4
}
f(z);
g();
k();
g();
h();
g();
console.log(`final value of var a is ${a}`);
The below example works as you want (if i understood your question). Simply omit var before a in function k().
var a = 0;
var z = 1;
var x = 2;
var y = 4;
function f(n) {
a = n;
}
function g(){
console.log(`value of var a is ${a}`); // output var a value to console
}
function h(){
f(x); // a becomes 2 here since x = 2
g(); // output var a value to console
}
function k() {
a = 0; // this sets a to 0 only in function scope
console.log(`function scope value of var a is ${a}`);
g(); // output var a value to console which is 1 here not 0
f(y); // a becomes 4 here since y = 4
}
f(z);
g();
k();
g();
h();
g();
console.log(`final value of var a is ${a}`);

Related

Same C code different results TIv5.2.5 and gcc 5.4.1 c99 compiler

I am using MSP432P401R to do FFT of SAR ADC samples, did FFT in MATLAB and got results same as C compiler online but Code Composer Studio IDE is giving different output than MATLAB results, I thought that can be a compiler issue so tried reading same did some changes and tried but not getting results Like MATLAB.
Online C compiler was gcc 5.4.1 c99.
and in CCS TI v5.2.5 compiler is used.
float m;
float ur, ui, sr, si,tr, ti;
long double Temp_A[256],ArrayA[256]={2676,2840,2838,2832,2826,2818,2814,2808,
2804,2798,2790,2784,2778,2770,2764,2758,2752,2746,2740,2734,
2726,2720,2714,2706,2700,2692,2686,2680,2674,2668,2660,2654,
2646,2642,2634,2624,2618,2612,2604,2598,2590,2584,2576,2570,
2562,2556,2550,2542,2536,2530,2522,2512,2508,2498,2490,2484,
2478,2470,2462,2454,2448,2442,2432,2426,2420,2414,2404,2398,
2390,2382,2374,2368,2360,2352,2346,2338,2330,2322,2314,2306,
2300,2294,2286,2278,2272,2262,2258,2250,2238,2234,2228,2220,
2208,2202,2192,2186,2178,2170,2164,2156,2150,2142,2134,2126,
2116,2110,2104,2096,2088,2078,2070,2062,2054,2046,2040,2034,
2026,2018,2010,2002,1994,1986,1978,1970,1962,1954,1946,1936,
1930,1922,1914,1908,1902,1894,1886,1876,1868,1860,1852,1846,
1838,1830,1822,1814,1804,1796,1790,1784,1776,1768,1760,1754,
1746,1738,1728,1720,1714,1708,1698,1692,1684,1674,1668,1656,
1656,1644,1640,1628,1624,1612,1610,1598,1596,1584,1580,1570,
1564,1554,1546,1540,1532,1526,1520,1512,1504,1496,1490,1482,
1474,1468,1462,1454,1446,1438,1432,1424,1420,1410,1404,1398,
1392,1384,1376,1370,1364,1356,1348,1342,1336,1328,1322,1316,
1308,1300,1294,1286,1280,1276,1270,1262,1254,1248,1242,1236,
1230,1222,1216,1210,1206,1198,1192,1188,1178,1172,1168,1162,
1154,1148,1144,1138,1132,1126,1120,1114,1108,1102,1096,1090,
1084,1080,1074,1068,1062,1058,1052,1048},ArrayA_IMX[256]={0};
unsigned int jm1,i;
unsigned int ip,l;
void main(void)
{
WDT_A->CTL = WDT_A_CTL_PW |WDT_A_CTL_HOLD;
VCORE();
CLK();
P1DIR |= BIT5; //CLK--AD7352 OUTPUT DIRECTION
P1DIR |= BIT7; //CHIP SELECT--AD7352 OUTPUT DIRECTION
P5DIR &= ~BIT0; //SDATAA--AD7352 INPUT DIRECTION P5.0
P5DIR &= ~BIT2; //SDATAB--AD7352 INPUT DIRECTION P5.2
while(1)
{
bit_reversal(ArrayA);
fft(ArrayA,ArrayA_IMX);
}
}
void bit_reversal(long double REX[])
{
int i,i2,n,m;
int tx,k,j;
n = 1;
m=8;
for (i=0;i<m;i++)
{
n *= 2;
}
i2 = n >> 1;
j = 0;
for (i=0;i<n-1;i++)
{
if (i < j)
{
tx = REX[i];
//ty = IMX[i];
REX[i] = REX[j];
//IMX[i] = IMX[j];
REX[j] = tx;
//IMX[j] = ty;
}
k = i2;
while (k <= j)
{
j -= k;
k >>= 1;
}
j += k;
}
}
void fft(long double REX[],long double IMX[])
{
N = 256;
nm1 = N - 1;
nd2 = N / 2;
m = log10l(N) / log10l(2);
j = nd2;
for (l = 1; l <= m; l++)
{
le = powl(2, l);
le2 = le / 2;
ur = 1;
ui = 0;
// Calculate sine and cosine values
sr = cosl(M_PI/le2);
si = -sinl(M_PI/le2);
// Loop for each sub DFT
for (j = 1; j <= le2; j++)
{
jm1 = j - 1;
// Loop for each butterfly
for (i = jm1; i <= nm1; i += le)
{
ip = i + le2;
tr = REX[ip]*ur - IMX[ip]*ui;
ti = REX[ip]*ui + IMX[ip]*ur;
REX[ip] = REX[i] - tr;
IMX[ip] = IMX[i] - ti;
REX[i] = REX[i] + tr;
IMX[i] = IMX[i] + ti;
}
tr = ur;
ur = tr*sr - ui*si;
ui = tr*si + ui*sr;
}
}
}

How to get the hash key?

When I solve this question(149. Max Points on a Line) on leetcode, it have a bug when met this case:
Input [[0,0],[94911151,94911150],[94911152,94911151]]
Output 3
Expected 2
This is my code:
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
int maxPoints(vector<Point>& points) {
int size = points.size();
int ans = 0;
if (size == 0) return 0;
unordered_map<double, int> mp;
double k;
for (int i = 0; i < size; ++i) {
int num = 0;
for (int j = i + 1; j < size; ++j) {
if (points[i].x == points[j].x && points[i].y == points[j].y) {
num++;
continue;
}
// my question in below code.
// how can I get the hash key according to slope
if (points[j].x - points[i].x != 0)
k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); // calculate the slope.
else k = INT_MAX;
mp[k]++;
}
if (mp[k] == 0) mp[k] = 1, num--;
for (auto it = mp.begin(); it != mp.end(); ++it) {
if (it->second > ans) {
ans = it->second;
ans += num;
}
}
mp.clear();
}
return ans+1;
}
};
In above test case, when it calculate the slope with [0,0] and [94911151,94911150] it comeback k = 1. So I want to know how to get the right hash key to solve this problem?

coffeescript prime number generation

I am trying to generate prime numbers like this:
generatePrimeNumbersBelowN = (n) ->
for i in [2..n-1]
isPrime = true
for j in [2..i-1]
isPrime = false if i % j == 0
break if not isPrime
console.log(i, "is Prime Number.") if isPrime
generatePrimeNumbersBelowN(100);
I am getting prime numbers from 3 to 97, inclusive. I am new to JavaScript/CoffeeScript, so please tell me what's happening to 2?
Here's the generated JS code:
var generatePrimeNumbersBelowN;
generatePrimeNumbersBelowN = function(n) {
var i, isPrime, j, k, l, ref, ref1, results;
results = [];
for (i = k = 2, ref = n - 1; 2 <= ref ? k <= ref : k >= ref; i = 2 <= ref ? ++k : --k) {
isPrime = true;
for (j = l = 2, ref1 = i - 1; 2 <= ref1 ? l <= ref1 : l >= ref1; j = 2 <= ref1 ? ++l : --l) {
if (i % j === 0) {
isPrime = false;
}
if (!isPrime) {
break;
}
}
if (isPrime) {
results.push(console.log(i, "is Prime Number."));
} else {
results.push(void 0);
}
}
return results;
};
generatePrimeNumbersBelowN(100);
generatePrimeNumbersBelowN = (n) ->
for i in [2..n-1]
isPrime = true
for j in [2..i-1]
isPrime = false if i % j == 0
break if not isPrime
console.log(i, "is Prime Number.") if isPrime
When i is 2, j ranges from 2 down to 1. You then check i % j which is 2 % 1 which is zero and claim that 2 is not a prime.
Because for x in [b..a] delivers a downward loop from b to a, while loop construct solves this problem.
generatePrimeNumbersBelowN = (n) ->
i = 2
while i < n
isPrime = true
j = 2
while j < i
isPrime = false if i % j == 0
break if not isPrime
j++
console.log(i, "is Prime Number.") if isPrime
i++
generatePrimeNumbersBelowN(100);

How can I get a reValue in a specific position of the matrix?

I'm new in sprite kit. I'm taking the value at a specific position of a matrix, but I really have a problem when I print that value. The simulator prints: optional(nil value) instead of printing just the value.
So, how can I get the reValue in a specific position of the matrix?
Code:
NumColumns = 4
NumRows = 4
func matrix() {
var valor = "0"
var principal = "0"
for var column = 0; column < NumColumns; column++ {
for var j = 0; j < NumRows; j++ {
valor = "\(numbers[column, j])"
cont++
principal = "\(cont)"
if valor != "0" {
numbers[column, j] = valor + principal
println("\(numbers[column, j])") //This print show: optional(nil >value)
}
else {
numbers[column, j] = principal
}
}
}
}
You can create a two-dimensional matrix of strings with the following:
var numColumns = 4
var numRows = 4
// Create a 4x4 matrix of Strings
var array = [[String]](count: numColumns, repeatedValue:[String](count: numRows, repeatedValue:String()))
// Assign a string to a matrix element
array[1][2] = "element at (1,2)"
println (array[1][2])

Matlab N-Queen Problem

main.m
counter = 1;
n = 8;
board = zeros(1,n);
back(0, board);
disp(counter);
sol.m
function value = sol(board)
for ( i = 1:(length(board)))
for ( j = (i+1): (length(board)-1))
if (board(i) == board(j))
value = 0;
return;
end
if ((board(i) - board(j)) == (i-j))
value = 0;
return;
end
if ((board(i) - board(j)) == (j-i))
value = 0;
return;
end
end
end
value = 1;
return;
back.m
function back(depth, board)
disp(board);
if ( (depth == length(board)) && (sol2(board) == 1))
counter = counter + 1;
end
if ( depth < length(board))
for ( i = 0:length(board))
board(1,depth+1) = i;
depth = depth + 1;
solv2(depth, board);
end
end
I'm attempting to find the maximum number of ways n-queen can be placed on an n-by-n board such that those queens aren't attacking eachother. I cannot figure out the problem with the above matlab code, i doubt it's a problem with my logic since i've tested out this logic in java and it seems to work perfectly well there. The code compiles but the issue is that the results it produces are erroneous.
Java Code which works:
public static int counter=0;
public static boolean isSolution(final int[] board){
for (int i = 0; i < board.length; i++) {
for (int j = i + 1; j < board.length; j++) {
if (board[i] == board[j]) return false;
if (board[i]-board[j] == i-j) return false;
if (board[i]-board[j] == j-i) return false;
}
}
return true;
}
public static void solve(int depth, int[] board){
if (depth == board.length && isSolution(board)) {
counter++;
}
if (depth < board.length) { // try all positions of the next row
for (int i = 0; i < board.length; i++) {
board[depth] = i;
solve(depth + 1, board);
}
}
}
public static void main(String[] args){
int n = 8;
solve(0, new int[n]);
System.out.println(counter);
}
Worked code:
function queen
clc;
counter = 0;
n = 8;
board = zeros(1,n);
[board,counter] = back(1, board,counter);
fprintf('Solution count: %d\n',counter);
%%
function value = isSolution(board)
for i = 1:length(board)
for j = (i+1): length(board)
if abs(board(i) - board(j)) == abs(i-j)
value = false;
return;
end
end
end
value = true;
%%
function [board,counter] = back(depth, board,counter)
if (depth == length(board)+1) && isSolution(board)
counter = counter + 1;
disp(board);
end
if ( depth <= length(board))
for i = 1:length(board)
if ~any(board==i)
board(1,depth) = i;
[~,counter] = back(depth+1, board,counter);
end
end
end
I add line if ~any(board==i), without this check, I think your java solution slower than this Matlab code. For fastest solution google "Dancing links".
There are many problems with your code.
Here are just a few:
you initialize board as 1-by-8 array
you call functions sol2 and solv2 that are undefined
no output is captured for solv2, or back (remember, Matlab passes variables by value, not by reference)
there are no comments in the code that would explain what you think you're doing and why you'd want to do that.
Also: While Matlab has a JIT compiler that, among others, helps speed up loops, Matlab code can't be said to "compile" (unless you're doing something dramatically wrong).