Length of arrays in matrices (Page 1) ● SmileBASIC Source Forums

Register
• #2 ✎ 91 Simeon Scholar Received for knowing a great deal about programming topics Achievements Amazing Page Hidden Achievements Drawing I like to draw! Hobbies Here is the code: ```DEF SIZE A OUT X,Y VAR T=A[1,0],B[0],L=LEN(A) A[1,0]=1<<31 COPY B,A FOR Y=0 TO L-1 IF B[Y]==A[1,0] THEN BREAK NEXT A[1,0]=T X=L/Y END``` Usage:```DIM MYARRAY[12,8] SIZE MYARRAY OUT X,Y ?"DIM MYARRAY[";X;",";Y;"]"``` How it works: When you have a two dimensional array, copying it to a new array will convert it into a one dimensional array. So we can change the value in [1,0] and see what index it gets mapped to. That will give us the size of one dimension, we can easily calculate the other. Note: The smallest array that this works on is [2,1]. The time complexity of this algorithm is O(X*Y+X), copying the whole array is linear, then we have to loop through Y once more, to get O(X*(Y+1)). I believe this is the fastest algorithm to do this. I'd love to see if someone can do better. Posted Edited by Simeon
• #6 ✎ 91 Simeon Scholar Received for knowing a great deal about programming topics Achievements Amazing Page Hidden Achievements Drawing I like to draw! Hobbies Well, okay, although it's a fun programming challenge, you have no reason to calculate the dimensions of a two dimensional array since you'll need those dimensions to initialize it in the first place. ```VAR W=8,H=12 VAR MYARRAY[H,W] ?"Width: ";W ?"Height: ";H``` Typing a "?" is the same thing as typing "PRINT", it's just easier to use Inside a print statement, we can use ";" to concatenate variables. Also note that VAR and DIM are the same. Posted Edited by Simeon
• #7 ✎ 91 Simeon Scholar Received for knowing a great deal about programming topics Achievements Amazing Page Hidden Achievements Drawing I like to draw! Hobbies ``` 'Make a function named SIZE that takes in 'a variable and outputs two variables X and Y DEF SIZE A OUT X,Y 'T is a temporary backup of A[1,0] 'B is an empty array 'L is width*height VAR T=A[1,0],B[0],L=LEN(A) 'Set A[1,0] to -2147483648 (bitshifting) A[1,0]=1<<31 'Copy the contents of A into B 'setting B's size to width*height COPY B,A 'Y will loop from 0 to width*height-1 FOR Y=0 TO L-1 'Check if we reach the -2147483648 inside B 'Once we do, break out of the loop 'Then Y will be the index of -2147483648 IF B[Y]==A[1,0] THEN BREAK NEXT 'Put back the value inside of A[1,0] A[1,0]=T 'width=width*height/height X=L/Y END ``` Posted Edited by Simeon
• #10 ✎ 125 niconii Video Games I like to play video games! Hobbies Expert Programmer Programming no longer gives me any trouble. Come to me for help, if you like! Programming Strength Drawing I like to draw! Hobbies `VAR T=A[1,0],B[0],L=LEN(A)` is the same as ```VAR T=A[1,0] VAR B[0] VAR L=LEN(A)``` Posted