Finding the range from an array - Recursive version - recursion

Here is my iterative algorithm. I want to write a recursive version
Make A an array of size n
Make min = infinity and make max = -infinity
For i from 0 to n-1
If A[i] > max
max = A[i]
if A[i] < min
min = A[i]
Return max - min

const range = (arr, min, max, i) => {
if (i == arr.length) return [min, max];
if (arr[i] > max) return range(arr, min, arr[i], i + 1);
if (arr[i] < min) return range(arr, arr[i], max, i + 1);
};
console.log(
range(
[1, 2, 3, 4, 8, 99, 432, -123],
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
0
)
);

Related

Error: subscript out of bounds (knight's tour)

im new to R and im trying to solve for the minimum number of moves for a knight visit all the moves in a chess board.
I got the python code from:
https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
and i tried to translate it to r.
But i am always getting the error and I don't know where I went wrong.
This is my code:
chess = rep(-1, times = 64)
board = matrix(data = chess, nrow = 8, ncol = 8, byrow = TRUE)
move_x = c(2, 1, -1, -2, -2, -1, 1, 2)
move_y = c(1, 2, 2, 1, -1, -2, -2, -1)
board[1, 1] = 0
pos = 1
valid_move <- function (x, y, board) {
if (x >= 1 & y >= 1 & x <= 8 & y <= 8 & board[x, y] == -1) {
return (T)
}
return (F)
}
solve <- function (board, curr_x, curr_y, move_x, move_y, pos) {
if (pos == 64) {
return (T)
}
for (i in seq(1:8)) {
new_x = curr_x + move_x[i]
new_y = curr_y + move_y[i]
if (valid_move(new_x, new_y, board)) {
board[new_x, new_y] = pos
if (solve(board, new_x, new_y, move_x, move_y, pos+1)) {
return (TRUE)
}
board[new_x, new_y] = -1
}
}
}
main <- function() {
sims = 10
ctr = 0
number_of_moves = c()
solve(board, 1, 1, move_x, move_y, pos)
print(paste("Minimum number of moves: ", pos))
}
main()
Thanks!
The problem is that the python code relies on short-circuiting to prevent out-of-bounds errors. & will not short-circuit so you need to use &&.
Here is an example
FALSE && stop()
#> [1] FALSE
FALSE & stop()
#> Error:
Update valid_move to this
valid_move <- function (x, y, board) {
# Changed to && to allow short-circuiting
# if (x >= 1 & y >= 1 & x <= 8 & y <= 8 & board[x, y] == -1) {
if (x >= 1 && y >= 1 && x <= 8 && y <= 8 && board[x, y] == -1) {
return (T)
}
return (F)
}

Calculating a determinant in Lua

I'm trying to calculate determinants with any order using Lua. I can calculate determinants for order less than 4, but not for greater equals than 4 ones.
I have a 4x4 matrix and its determinant with the program is 0, but the real solution is 56.
I don't know if the problem is in getSubmatrix method or is in detMat method, because I don't have any error message from the console.
I've ported the methods from my own java code, where it works fine.
Here's all my code:
function numMat(n, A)
local S = {}
for i = 1, #A, 1 do
local T = {}
S[i] = T
for j =1, #A[1], 1 do
T[j] = n * A[i][j]
end
end
return S
end
function sumMat(A, B)
local C = {}
for i = 1, #A do
local D = {}
C[i] = D
for j = 1, #A[1] do
D[j] = A[i][j] + B[i][j]
end
end
return C
end
function subMat(A, B)
return sumMat(A, numMat(-1, B))
end
function printMatrix(A)
for i, v in ipairs(A) do
for j, w in ipairs(v) do
print(w)
end
end
end
function escalarProduct(u, v)
local w = 0
for i = 1, #u do
w = w + u[i] * v[i]
end
return w
end
function prodMat(A, B)
local C = {}
for i = 1, #A do
C[i] = {}
for j = 1, #B[1] do
local num = A[i][1] * B[1][j]
for k = 2, #A[1] do
num = num + A[i][k] * B[k][j]
end
C[i][j] = num
end
end
return C
end
function powMat(A, power)
local B = {}
local C = {}
C = A
for i = 1, power - 1 do
B = prodMat(C, A)
C = B
end
return B
end
function trasposeMat(A)
local B = {}
for i = 1, #A do
local C = {}
B[i] = C
for j = 1, #A[1] do
C[j] = A[j][i]
end
end
return B
end
function productDiag(m)
local prod = 1
for i = 1, #m do
for j = 1, #m do
if i == j then prod = prod * m[i][i] end
end
end
return prod
end
function isDiagonal(A)
for i = 1, #A do
for j = 1, #A do
if i ~= j and A[i][j] ~= 0 then return false end
end
end
return true
end
function isTriangSup(m)
for i = 1, #m do
for j = 1, i do
if m[i][j] == 0 then return true end
end
end
return false
end
function isTriangInf(m)
return isTriangSup(trasposeMat(m))
end
function isTriang(m)
if(isTriangSup(m)) then return true
else
return false
end
end
function getSubmatrix(A, rows, cols, col)
local submatrix = {}
local k = 1
for j = 1, cols do
--local D = {}
--submatrix[j] = D
if j == col then
break
end
for i = 2, rows do
submatrix[i-1][k] = A[i][j]
--D[k] = A[i][j]
end
k = k + 1
end
return submatrix
end
function det2Mat(A)
assert(#A == 2 and #A == #A[1], 'Error: The matrix must be squared, order 2.')
return A[1][1] * A[2][2] - A[1][2] * A[2][1]
end
function det3Mat(A)
assert(#A == 3 and #A == #A[1], 'Error: The matrix must be squared, order 3.')
s1 = A[1][1] * A[2][2] * A[3][3] + A[2][1] * A[3][2] * A[1][3] + A[1][2] * A[2][3] * A[3][1]
s2 = A[1][3] * A[2][2] * A[3][1] + A[1][2] * A[2][1] * A[3][3] + A[2][3] * A[3][2] * A[1][1]
return s1 - s2
end
function detMat(A)
local submatrix = {}
local det
local sign = 1
local rows = #A
local cols = #A[1]
assert(rows == cols, 'Error: The matrix must be squared.')
if rows == 1 then
return A[1][1]
end
if rows == 2 then
return det2Mat(A)
end
if rows == 3 then
return det3Mat(A)
end
if isDiagonal(A) or isTriang(A) then return productDiag(A) end
if rows > 3 then
for column = 1, cols do
submatrix = getSubmatrix(A, rows, cols, column)
det = det + sign * A[1][column] * detMat(submatrix)
sign = -sign
end
end
return det
end
A = {{1, 3}, {5, 6}}
B = {{2, 4}, {3, 1}}
C = {{2, 3, 4}, {-5, 4, 7}, {7, 1, 0}}
D = {{2, 0, 0, 0}, {0, 4, 0, 0}, {0, 0, 7, 0}, {0, 0, 0, 6}}
E = {{2, 3, 4, -3}, {-5, 4, 7, -2}, {7, 1, 0, 5}, {3, 4, 5, 6}}
--printMatrix(numMat(-1, A))
--printMatrix(sumMat(A, B))
--printMatrix(subMat(A, B))
--print(escalarProduct({1, 3}, {5, 6}))
--printMatrix(prodMat(A, B))
--printMatrix(trasposeMat(A))
--printMatrix(powMat(A, 2))
--printMatrix(powMat(A, 3))
print(detMat(A))
print(detMat(B))
print(detMat(C))
print(detMat(D))
print(detMat(E)) --The solution must be 56
And the console solution is:
-9
-10
1
336
0
The error is when I want to find out the determinant of the matrix E.

C++ Multidimensional Array help delete a row and column

I need someone to tell me how to write a code easy and understandable for this matrix
In this exercise is search to delete a row and a column:
const int n = 4, m = 4;
int A[n][m] = { { 2, -8, -7, 5 },{ 4, -7, -8, 2 },{ 1, 10, 3, 6 },{ 4, 7, 9, -3 } };
int i, j, r, k, B[n][m];
variable r stands for row which need to be deleted
variable k stands for column which needs to be deleted
B[n][m] stands for new matrix that will be showed on console
Waiting for answer
there's my code :
const int n = 4, m = 4;
int A[n][m] = { { 2, -8, -7, 5 },
{ 4, -7, -8, 2 },
{ 1, 10, 3, 6 },
{ 4, 7, 9, -3 } };
int i, j, r, k, B[n][m];
cout << "give a value r and k:";
cin >> r >> k;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
if ((i < r) && (j < k))
B[i][j] = A[i][j];
if ((i >= r) && (j < k))
B[i][j] = A[i + 1][j];
if ((i < r) && (j >= k))
B[i][j] = A[i][j + 1];
if ((i >= r) && (j >= k))
B[i][j] = A[i + 1][j + 1];
}
}
cout << "Matrix B ={" << endl;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < m - 1; j++)
{
cout.width(3);
cout << B[i][j];
}
cout << endl;
but here is what mix up things to me :
if ((i < r) && (j < k))
B[i][j] = A[i][j];
if ((i >= r) && (j < k))
B[i][j] = A[i + 1][j];
if ((i < r) && (j >= k))
B[i][j] = A[i][j + 1];
if ((i >= r) && (j >= k))
B[i][j] = A[i + 1][j + 1];
}
this is the part where i mess up more often
Can somebody tell me more easier way ?

Are there any description about using "fit image" function (DM FitTools) in script?

I would like to integrate the functions provided by the "Fit Image" plattlet (especially 2D polynomial fit to a given input image and subtract it) in DM to script to automate the whole flow of image processing.
However, I could not find any description of how to do it.
It's appreciated if anyone know it, or have certain documentaion on this.
The script functionality for fitting is not yet officially supported/documented.
However, you can use the following examples to see how the commands work:
Commands
Boolean FitGaussian(Image* data, Image* errors, double* N, double* mu, double* sigma, double* chiSqr, double conv_cond)
ImageRef PlotGaussian(Image* data, double N, double mu, double sigma)
Boolean FitLorentzian(Image* data, Image* errors, double* I, double* x0, double* gamma, double* chiSqr, double conv_cond)
ImageRef PlotLorentzian(Image* data, double I, double x0, double gamma)
Boolean FitPolynomial(Image* data, Image* errors, Image* pars, Image* parsToFit, double* chiSqr, double conv_cond)
ImageRef PlotPolynomial(Image* data, Image* pars)
Boolean FitGaussian2D(Image* data, Image* errors, Image* pars, Image* parsToFit, double* chiSqr, double conv_cond)
ImageRef PlotGaussian2D(Image* data, Image* pars)
Boolean FitPolynomial2D(Image* data, Image* errors, Image* pars, Image* parsToFit, double* chiSqr, double conv_cond)
ImageRef PlotPolynomial2D(Image* data, Image* pars)
Boolean FitFormula(dm_string formulaStr, Image* data, Image* errors, Image* pars, Image* parsToFit, double* chiSqr, double conv_cond)
ImageRef PlotFormula(dm_string formulaStr, Image* data, Image* pars)
example 1, 1D formula fit
// create the input image:
Image input := NewImage("formula test", 2, 100)
input = 500.5 - icol*11.1 + icol*icol*0.11
// add some random noise:
input += (random()-0.5)*sqrt(abs(input))
// create image with error data (not required)
Image errors := input.ImageClone()
errors = tert(input > 1, sqrt(input), 1)
// setup fit:
Image pars := NewImage("pars", 2, 3)
Image parsToFit := NewImage("pars to fit", 2, 3)
pars = 10; // starting values
parsToFit = 1;
Number chiSqr = 1e6
Number conv_cond = 0.00001
Result("\n starting pars = {")
Number xSize = pars.ImageGetDimensionSize(0)
Number i = 0
for (i = 0; i < xSize; i++)
{
Result(GetPixel(pars, i, 0))
if (i < (xSize-1)) Result(", ")
}
Result("}")
// fit:
String formulaStr = "p0 + p1*x + p2*x**2"
Number ok = FitFormula(formulaStr, input, errors, pars, parsToFit, chiSqr, conv_cond)
Result("\n results pars = {")
for (i = 0; i < xSize; i++)
{
Result(GetPixel(pars, i, 0))
if (i < (xSize-1)) Result(", ")
}
Result("}")
Result(", chiSqr ="+ chiSqr)
// plot results of fit:
Image plot := PlotFormula(formulaStr, input, pars)
// compare the plot and original data:
Image compare := NewImage("Compare Fit", 2, 100, 3)
compare[icol, 0] = input // original data
compare[icol, 1] = plot // fit function
compare[icol, 2] = input - plot // residuals
ImageDocument linePlotDoc = CreateImageDocument("Test Fitting")
ImageDisplay linePlotDsp = linePlotDoc.ImageDocumentAddImageDisplay(compare, 3)
linePlotDoc.ImageDocumentShow()
example 2, 2D Gaussian fit
// $BACKGROUND$
// create data image
Image img := NewImage("Gaussian2D", 2, 200, 200)
Image true_pars := NewImage("Gaussian2D Pars", 2, 6)
// true parameters
true_pars[0,0] = 1000 // height of gaussian
true_pars[1,0] = 60 // center in x
true_pars[2,0] = 50 // width in x
true_pars[3,0] = 40 // center in y
true_pars[4,0] = 80 // width in y
true_pars[5,0] = 0.7 // rotation in radians
Image data := PlotGaussian2D(img, true_pars)
data += (gaussianrandom())*sqrt(abs(data)) //add noise
ShowImage(data)
Image errors := data.ImageClone()
errors = tert(abs(data) > 1, sqrt(abs(data)), 1)
// starting parameters of fit
Image pars := NewImage("Gaussian2D Pars", 2, 6)
pars = 100
pars[0,0] = max(data) // estimate normalization from peak of data
pars[5,0] = 0 // 100 radians doesn't make sense
Image parsToFit := NewImage("tmp", 2, 6)
parsToFit = 1
Number chiSqr = 1e6
Number conv_cond = 0.00001
Result("\n starting pars = {")
Number xSize = pars.ImageGetDimensionSize(0)
Number i = 0
for (i = 0; i < xSize; i++)
{
Result(GetPixel(pars, i, 0))
if (i < (xSize-1)) Result(", ")
}
Result("}")
// fit
Number ok = FitGaussian2D(data, errors, pars, parsToFit, chiSqr, conv_cond)
if (chiSqr > 2)
ok = FitGaussian2D(data, errors, pars, parsToFit, chiSqr, conv_cond)
Image parDif = 100.0*(pars - true_pars)/true_pars
Result("\n results pars (% dif from true)= {")
for (i = 0; i < xSize; i++)
{
Result(GetPixel(parDif, i, 0))
if (i < (xSize-1)) Result(", ")
}
Result("}")
Result(", chiSqr ="+ chiSqr)
// show residuals
Image residuals := PlotGaussian2D(img, pars)
residuals = data - residuals
ShowImage(residuals)
example 3, 2D Polynomial fit
// $BACKGROUND$
// The number of parameters are defined by the order,
// nPar = (order+1)*(order+2)/2. For example, a
// 3rd order poly will have (3+1)*(3+2)/2 = 10 parameters:
//
// x^0 x^1 x^2 x^3
// --------------------------------
// y^0 | p0 p1 p2 p3
// y^1 | p4 p5 p6 -- (the -- terms are higher)
// y^2 | p7 p8 -- -- (order so are ignored )
// y^3 | p9 -- -- --
//
//
// i.e. f(x,y|p) = p0 + p1*x + p2*x^2 + p3*x^3 + p4*y + p5*x*y
// + p6*x^2*y + p7*y^2 + p8*x*y^2 + p9*y^3
Number xImgSize = 512
Number yImgSize = 512 // create data image
Image img := NewImage("Poly2D", 2, xImgSize, yImgSize)
Image pars_true := NewImage("Poly2D Pars", 2, 3, 3)
// true parameters
pars_true[0,0] = 100
pars_true[1,0] = 60
pars_true[2,0] = -0.05
pars_true[0,1] = 70
pars_true[1,1] = 0.01
pars_true[0,2] = -0.1
Image data := PlotPolynomial2D(img, pars_true)
data += (gaussianrandom())*sqrt(abs(data)) //add noise
ShowImage(data)
Image errors := data.ImageClone()
errors = tert(abs(data) > 1, sqrt(abs(data)), 1)
// starting parameters of fit
Image pars := NewImage("Poly2D Pars", 2, 3, 3)
pars = 10
Image parsToFit := NewImage("tmp", 2, 3, 3)
parsToFit = 1
Number chiSqr = 1e6
Number conv_cond = 0.00001
Result("\n starting pars = {")
Number xSize = pars.ImageGetDimensionSize(0)
Number ySize = pars.ImageGetDimensionSize(1)
Number i, j
for (j = 0; j < ySize; j++)
{
if (j > 0) Result(", ")
Result("{")
for (i = 0; i < xSize; i++)
{
if (i > 0) Result(", ")
if ((i+j) > 2)
Result("-")
else
Result(GetPixel(pars, i, j))
}
Result("}")
}
Result("}")
// fit
Number startTicks = GetHighResTickCount()
Number ok = FitPolynomial2D(data, errors, pars, parsToFit, chiSqr, conv_cond)
Number endTicks = GetHighResTickCount()
Number secs = CalcHighResSecondsBetween(startTicks, endTicks)
Image parDif = 100*(pars - pars_true)/pars_true
Result("\n results pars (% diff from true) = {")
for (j = 0; j < ySize; j++)
{
if (j > 0) Result(", ")
Result("{")
for (i = 0; i < xSize; i++)
{
if (i > 0) Result(", ")
if ((i+j) > 2)
Result("-")
else
Result(GetPixel(parDif, i, j))
}
Result("}")
}
Result("}")
Result(", chiSqr = "+ chiSqr)
Result(", Fit Time (s) = " + secs)
// show residuals
Image residuals := PlotPolynomial2D(img, pars)
residuals = data - residuals
ShowImage(residuals)

Function Plotter error in Dart (with three.dart): Breaking on exception: The null object does not have a method 'crossInto'

The calculations are done in the following code:
var MIN = -10.0,
MAX = 10.0,
RANGE = MAX - MIN;
getColor(max, min, val) {
var MIN_L = 40,
MAX_L = 100;
var color = new Color();
var h = 0 / 240;
var s = 80 / 240;
var l = (((MAX_L - MIN_L) / (max - min)) * val) / 240;
color.setHSL(h, s, l);
return color;
}
initGraph() {
var x = MIN,
y = MIN,
z = 0.0;
initData() {
var data = [];
for (var i = MIN; i < MAX; i++) {
var row = [];
for (var j = MIN; j < MAX; j++) {
double z = 2*( x * x + y * y);
print('$z');
row.add({
x: x,
y: y,
z: z
});
y++;
}
data.add(row);
x++;
}
return data;
}
var data = initData();
var geometry = new Geometry();
var colors = [];
var RANGE = data.length,
height = data[0].length;
data.forEach((col) {
col.forEach((val) {
geometry.vertices.add(new Vector3(x.toDouble(), y.toDouble(), z.toDouble()));
colors.add(getColor(2.5, 0, z.toDouble()));
});
});
offset(x, y) {
return x * RANGE + y;
}
for (var x = 0; x < RANGE - 1; x++) {
for (var y = 0; y < height - 1; y++) {
Vector3 vec0;
Vector3 vec1;
Vector3 n_vec;
// one of two triangle polygons in one rectangle
vec0 = (geometry.vertices[offset(x, y)] - geometry.vertices[offset(x + 1, y)]);
vec1 = (geometry.vertices[offset(x, y)] - geometry.vertices[offset(x, y + 1)]);
n_vec.crossInto(vec0, vec1).normalize();
geometry.faces.add(new Face3(offset(x, y), offset(x + 1, y), offset(x, y + 1), n_vec, [colors[offset(x, y)], colors[offset(x + 1, y)], colors[offset(x, y + 1)]]));
geometry.faces.add(new Face3(offset(x, y), offset(x, y + 1), offset(x + 1, y), n_vec.negate(), [colors[offset(x, y)], colors[offset(x, y + 1)], colors[offset(x + 1, y)]]));
// the other one
vec0 = (geometry.vertices[offset(x + 1, y)] - geometry.vertices[offset(x + 1, y + 1)]);
vec1 = (geometry.vertices[offset(x, y + 1)] - geometry.vertices[offset(x + 1, y + 1)]);
n_vec.crossInto(vec0, vec1).normalize();
geometry.faces.add(new Face3(offset(x + 1, y), offset(x + 1, y + 1), offset(x, y + 1), n_vec, [colors[offset(x + 1, y)], colors[offset(x + 1, y + 1)], colors[offset(x, y + 1)]]));
geometry.faces.add(new Face3(offset(x + 1, y), offset(x, y + 1), offset(x + 1, y + 1), n_vec.negate(), [colors[offset(x + 1, y)], colors[offset(x, y + 1)], colors[offset(x + 1, y + 1)]]));
}
}
var material = new MeshLambertMaterial(vertexColors: VertexColors);
var mesh = new Mesh(geometry, material);
scene.add(mesh);
}
The error seems to be on the occurrence of this line:
n_vec.crossInto(vec0, vec1).normalize();
What is the null object here and how do I solve this? Could the variable 'z' be causing the issue? It first showed null, and caused a similar error (that '*' cannot be applied) and I declared it as double and that got solved. I also have a suspicion in the below lines:
data.forEach((col) {
col.forEach((val) {
geometry.vertices.add(new Vector3(x.toDouble(), y.toDouble(), z.toDouble()));
n_vec is never initialized with an instance of Vector3. crossInto requires to be called on an instance, Either you create an instance first:
Vector3 n_vec = new Vector3.zero();
...
n_vec.crossInto(vec0, vec1).normalize();
Or you use the cross method, but it creates a new instance of Vector3 (you might want to avoid new instances, than I would move the variables out of the loop):
n_vec = vec0.cross(vec1).normalize();

Resources