Split a rectangle like a mosaic - math

I try since yesterday to build a function which divide a rectangle like this :
n = 1
____________
| |
|____________|
n = 2
____________
|____________|
|____________|
n = 3
____________
|______|_____|
|____________|
n = 4
____________
|______|_____|
|______|_____|
n = 5
____________
|__ |__|_____|
|______|_____|
I've search but not found any algorithm name.
At the end I want something like an array with the (x, y, Long, larg) of each rectangle.
I think it's something recursive with just some divisions by 2 but... I haven't found any solution of my problem.
So if you have just some tips for me (not an entire code) I will really appreciate that.
Sorry if my English is bad, if you want some precision don't hesitate.
Raph.
EDIT :
n = 5 is more like that :
____________
|______| |
|______|_____|
|______|_____|
EDIT 2 : Here is the code I did working until 8 separations
PROCEDURE TrouveCoordsV2(nImages is int, nNoEcran is int)
listeEcran is string = SysListScreen()
tabNoms is array of strings = StringSplit(listeEcran,CR)
tabResolutionInt is array of strings = StringSplit(SysScreenResolution(tabNoms[nNoEcran]), TAB)
tabResolutionEcran is array of int
dimensionsEcran is array of int
FOR i = 1 TO 2
ArrayAdd(dimensionsEcran, Val(tabResolutionInt[i]))
END
ArrayAdd(tabResolutionEcran, TrouvePositionEcranX(nNoEcran, SysScreenRectangle()))
ArrayAdd(tabResolutionEcran, 0)
ArrayAdd(tabResolutionEcran, dimensionsEcran)
INTERNAL PROCEDURE CalculResolution(n is int, resolution is array of int)
tabResultat is array of arrays of int = []
nLongueur is int = RoundDown(resolution[3]/2)
nLargeur is int = RoundDown(resolution[4]/2)
resHG, resHD, resBG, resBD, resHL, resBL are arrays of int
resHG = [resolution[1], resolution[2], nLongueur, nLargeur]
resHD = [resolution[1]+nLongueur, resolution[2], nLongueur, nLargeur]
resBG = [resolution[1], resolution[2]+nLargeur, nLongueur, nLargeur]
resBD = [resolution[1]+nLongueur, resolution[2]+nLargeur, nLongueur, nLargeur]
resHL = [resolution[1], resolution[2], resolution[3], nLargeur]
resBL = [resolution[1], resolution[2]+nLargeur, resolution[3], nLargeur]
SWITCH n
CASE 1
ArrayAdd(tabResultat, resolution)
RESULT tabResultat
CASE 2
ArrayAdd(tabResultat, resHL)
ArrayAdd(tabResultat, resBL)
RESULT tabResultat
CASE 3
ArrayAdd(tabResultat, resHL)
ArrayAdd(tabResultat, resBG)
ArrayAdd(tabResultat, resBD)
RESULT tabResultat
CASE 4
ArrayAdd(tabResultat, resHG)
ArrayAdd(tabResultat, resHD)
ArrayAdd(tabResultat, resBG)
ArrayAdd(tabResultat, resBD)
RESULT tabResultat
CASE >4
mod is int = modulo(n, 4)
SWITCH mod
CASE 0
ArrayAdd(tabResultat, CalculResolution(n-6, resHG))
ArrayAdd(tabResultat, CalculResolution(n-6, resHD))
ArrayAdd(tabResultat, CalculResolution(n-6, resBG))
ArrayAdd(tabResultat, CalculResolution(n-6, resBD))
RESULT tabResultat
CASE 1
ArrayAdd(tabResultat, CalculResolution(n-5, resHG))
ArrayAdd(tabResultat, CalculResolution(n-5, resHD))
ArrayAdd(tabResultat, CalculResolution(n-5, resBG))
ArrayAdd(tabResultat, CalculResolution(n-3, resBD))
RESULT tabResultat
CASE 2
ArrayAdd(tabResultat, CalculResolution(n-6, resHG))
ArrayAdd(tabResultat, CalculResolution(n-6, resHD))
ArrayAdd(tabResultat, CalculResolution(n-4, resBG))
ArrayAdd(tabResultat, CalculResolution(n-4, resBD))
RESULT tabResultat
CASE 3
ArrayAdd(tabResultat, CalculResolution(n-7, resHG))
ArrayAdd(tabResultat, CalculResolution(n-5, resHD))
ArrayAdd(tabResultat, CalculResolution(n-5, resBG))
ArrayAdd(tabResultat, CalculResolution(n-5, resBD))
RESULT tabResultat
OTHER CASE
Info("Une erreur inattendue est survenue au niveau de l'affichage des fenetres")
END
CASE <=0
RESULT resolution
OTHER CASE
Info("Une erreur inattendue est survenue au niveau de l'affichage des fenetres")
END
END
IF nImages > 8 THEN
Info("Certaines aides n'ont pas pu êtres affichées")
nImages = 8
END
RESULT CalculResolution(nImages,tabResolutionEcran)
I will try to find a solution for n separations.
If you want me to explain my code tell me because in WinDev comments are in a weird yellow background and give me an headache...
So I translate it partially in English for you.
Thanks in advance, have a nice day
Raph.

You give no code or algorithm, and just ask for "some tips," so I'll just give a broad idea here. If you want me to expand on this idea, show more work of your own.
If your value of n, the number of small rectangles, is a composite number (let's say n = a * b), then you could easily make a big rectangle with sides a and b that will have n small rectangles.
If n is prime and greater than 3, then n-1 is composite. You could make a big rectangle with n-1 little rectangles, then split one of the small rectangles into to smaller rectangles. That's basically what you did in your examples for n=3 and n=5.
Note that no recursion is required. Of course, another possibility is just to draw a rectangle of size 1 by n, but that is not close to a square. If an additional goal is to get as close to a square as possible, then for composite n in my method you have the additional problem of finding a and b as close to each other as possible. (For example, if n is 12, you probably want a=4 and b=3 rather than a=2 and b=6.) I'll leave that problem to you.

string :- "Hello world"
I find a working solution here is the code
PROCEDURE TrouveCoordsV2(nImages is int, nNoEcran is int)
listeEcran is string = SysListScreen()
tabNoms is array of strings = StringSplit(listeEcran,CR)
tabResolutionInt is array of strings = StringSplit(SysScreenResolution(tabNoms[nNoEcran]), TAB)
tabResolutionEcran is array of int
dimensionsEcran is array of int
FOR i = 1 TO 2
ArrayAdd(dimensionsEcran, Val(tabResolutionInt[i]))
END
ArrayAdd(tabResolutionEcran, TrouvePositionEcranX(nNoEcran, SysScreenRectangle()))
ArrayAdd(tabResolutionEcran, 0)
ArrayAdd(tabResolutionEcran, dimensionsEcran)
INTERNAL PROCEDURE CalculResolution(n is int, resolution is array of int)
tabResultat is array of arrays of int = []
nLongueur is int = RoundDown(resolution[3]/2)
nLargeur is int = RoundDown(resolution[4]/2)
resHG, resHD, resBG, resBD, resHL, resBL are arrays of int
resHG = [resolution[1], resolution[2], nLongueur, nLargeur]
resHD = [resolution[1]+nLongueur, resolution[2], nLongueur, nLargeur]
resBG = [resolution[1], resolution[2]+nLargeur, nLongueur, nLargeur]
resBD = [resolution[1]+nLongueur, resolution[2]+nLargeur, nLongueur, nLargeur]
resHL = [resolution[1], resolution[2], resolution[3], nLargeur]
resBL = [resolution[1], resolution[2]+nLargeur, resolution[3], nLargeur]
IF n=1
ArrayAdd(tabResultat,resolution)
ELSE IF n=2
ArrayAdd(tabResultat,resBL)
ArrayAdd(tabResultat,resHL)
ELSE IF n=3
ArrayAdd(tabResultat,resBD)
ArrayAdd(tabResultat,resBG)
ArrayAdd(tabResultat,resHL)
ELSE IF n=4
ArrayAdd(tabResultat,resBD)
ArrayAdd(tabResultat,resBG)
ArrayAdd(tabResultat,resHD)
ArrayAdd(tabResultat,resHG)
ELSE IF n>4
tabNbImages is array of int = NbFenetresParEcrans(n,4)
tabResolutions is array of arrays of int
ArrayAdd(tabResolutions,resBD)
ArrayAdd(tabResolutions,resBG)
ArrayAdd(tabResolutions,resHD)
ArrayAdd(tabResolutions,resHG)
FOR i = 1 TO 4
ArrayAdd(tabResultat, CalculResolution(tabNbImages[i], tabResolutions[i]))
END
END
RESULT tabResultat
END
RESULT CalculResolution(nImages,tabResolutionEcran)
And there is the "NbFenetresParEcrans" function
PROCEDURE NbFenetresParEcrans(nNbFichiers is int, nNbEcrans is int)
tabFenetres is array of int = []
nDivision is int
nFichiersRestants is int = nNbFichiers
i is int = nNbEcrans
WHILE i > 0
nDivision = RoundUp(nFichiersRestants/i)
ArrayAdd(tabFenetres, nDivision)
nFichiersRestants -= nDivision
i--
END
RESULT tabFenetres
Thanks all for your help if you want precision I can give you.
Have a nice day and comments in WinDev give you good headache (:

Related

How to check if a number is palindrome in Clean

I am solving this homework of clean programming language;
The problem is we have a number of five digits and we want to check whether it's an odd palindrome or not.
I am stuck at the stage of dividing the number to five separate digits and perform a comparison with the original number, for the palindrome check. With Clean I can't loop over the number and check if it remains the same from the both sides, so I am looking for an alternative solution (Some mathematical operations).
Code block:
isOddPalindrome :: Int -> Bool
isOddPalindrome a
| isFive a <> 5 = abort("The number should be exactly five digits...")
| (/*==> Here should be the palindrome check <==*/) && (a rem 2 <> 0) = True
| otherwise = False
isFive :: Int -> Int
isFive n
| n / 10 == 0 = 1
= 1 + isFive(n / 10)
My idea is to take the number, append it's digits one by one to an empty list, then perform the reverse method on the list and check if it's the same number or not (Palindrome)
Your answer above doesn't have a stopping condition so it will result in stack overflow.
You could try this
numToList :: Int -> [Int]
numToList n
| n < 10 = [n]
= numToList (n/10) ++ [n rem 10]
Start = numToList 12345
and then like you mentioned in the answer, you can reverse it with the 'reverse' function and check if they are equal.
After hours of trying to figure out how to recursively add the digits of our number to an empty list, I did the following:
sepDigits :: Int [Int] -> [Int]
sepDigits n x = sepDigits (n/10) [n rem 10 : x]
Now I can easily check whether the reverse is equal to the initial list :) then the number is palindrome.

Return a list of even numbers from a list of integer pairs in sml

I have the following question "Given a list of integer pairs, write a function to return a list of even numbers in that list in sml".
this is what I've achieved so far
val x = [(6, 2), (3, 4), (5, 6), (7, 8), (9, 10)];
fun isEven(num : int) =
if num mod 2 = 0 then num else 0;
fun evenNumbers(list : (int * int) list) =
if null list then [] else
if isEven(#1 (hd list)) <> 0
then if isEven(#2 (hd list)) <> 0
then #1 (hd list) :: #1 (hd list) :: evenNumbers(tl list)
else []
else if isEven(#2 (hd list)) <> 0
then #1 (hd list) :: evenNumbers(tl list)
else [];
evenNumbers(x);
the result should be like this [6,2,4,6,8,10]
any help would be appreciated.
I see two obvious problems.
If both the first and second number are even, you do
#1 (hd list) :: #1 (hd list) :: evenNumbers(tl list)
which adds the first number twice and ignores the second.
If the first number is odd and the second even, you do
#1 (hd list) :: evenNumbers(tl list)
which adds the number that you know is odd and ignores the one you know is even.
Programming with selectors and conditionals gets complicated very quickly (as you've noticed).
With pattern matching, you could write
fun evenNumbers [] = []
| evenNumber ((x,y)::xys) = ...
and reduce the risk of using the wrong selector.
However, this still makes for complicated logic, and there is a better way.
Consider the simpler problem of filtering the odd numbers out of a list of numbers, not pairs.
If you transform the input into such a list, you only need to solve that simpler problem (and there's a fair chance that you've already solved something very similar in a previous exercise).
Exercise: implement this transformation. Its type will be ('a * 'a) list -> 'a list.
Also, your isEven is more useful if it produces a truth value (if you ask someone, "is 36 even?", "36" is a very strange answer).
fun isEven x = x mod 2 = 0
Now, evenNumbers can be implemented as "just" a combination of other, more general, functions.
So running your current code,
- evenNumbers [(6, 2), (3, 4), (5, 6), (7, 8), (9, 10)];
val it = [6,6,3,5,7,9] : int list
suggests that you're not catching all even numbers, and that you're catching some odd numbers.
The function isEven sounds very much like you want to have the type int -> bool like so:
fun isEven n =
n mod 2 = 0
Instead of addressing the logic error of your current solution, I would like to propose a syntactically much simpler approach which is to use pattern matching and fewer explicit type annotations. One basis for such a solution could look like:
fun evenNumbers [] = ...
| evenNumbers ((x,y)::pairs) = ...
Using pattern matching is an alternative to if-then-else: the [] pattern is equivalent to if null list ... and the (x,y)::pairs pattern matches when the input list is non-empty (holds at least one element, being (x,y). At the same time, it deconstructs this one element into its parts, x and y. So in the second function body you can express isEven x and isEven y.
As there is a total of four combinations of whether x and y are even or not, this could easily end up with a similarly complicated nest of if-then-else's. For this I might do either one of two things:
Use case-of (and call evenNumbers recursively on pairs):
fun evenNumbers [] = ...
| evenNumbers ((x,y)::pairs) =
case (isEven x, isEven y) of
... => ...
| ... => ...
Flatten the list of pairs into a list of integers and filter it:
fun flatten [] = ...
| flatten ((x,y)::pairs) = ...
val evenNumbers pairs = ...

minizinc sitting-friends-at-a-table-far-from-furius ones

1.we have cycling table
2.a man must be sit next to a woman and a woman next to a man
3. guests must share hobbies (at least one common between their hobbies)
4. there are couples of furious guests. they must not sit near to next to each other
5. nobody of list o furious guests must sit at start(seat 1) or end (seat N)
-pR is the number of furious couples
my model:
int :N;
set of int: GUESTS = 1..N;
set of int: POSITIONS = 1..N;
array[GUESTS] of 1..2 : gender;
array[GUESTS] of set of int: hobbies;
enum PAIR = {first,second};
int : pR;
set of int: LIST = 1..pR;
array[LIST,PAIR] of GUESTS : furious;
array[POSITIONS] of var GUESTS : guest_at;
array[POSITIONS] of var 1..2: table_gender;
constraint forall(i in 1..length(table_gender)-1)(
table_gender[i]!=table_gender[i+1]
/\
table_gender[1]!=table_gender[length(table_gender)]
)
;
include "alldifferent.mzn";
constraint alldifferent(guest_at);
constraint forall(i in 2..N-1)(card(hobbies[guest_at[i+1]] intersect hobbies[guest_at[i]]) >0);
constraint card(hobbies[guest_at[N]] intersect hobbies[guest_at[1]]) >0;
constraint forall(i in 2..N-1,l in LIST, p in PAIR)(if guest_at[i]=furious[i,first] then guest_at[i+1]!=furious[i,second] /\ guest_at[i-1]!=furious[i,second] else true endif);
constraint forall(l in LIST, p in PAIR)(guest_at[1]!=furious[l,p] /\ guest_at[N]!=furious[l,p]);
solve satisfy;
output
["guest_at = \(guest_at);"]
++ ["\ntable_gender = \(table_gender); \n" ]
++ ["Furious Placement\n"]
++ [show_int(4,furious[i,j]) | i in LIST, j in PAIR] ++["\n"]
++ [if fix(guest_at[p]) = furious[i,j] then show_int(4,p) else "" endif | i in LIST, j in PAIR, p in POSITIONS]
;
my model's bugs:
C:/Users/�������/Documents/������/����������/Gala/gala.mzn:36:
in call 'forall'
in array comprehension expression
with i = 4
with l = 3
with p = 1
in if-then-else expression
in binary '=' operator expression
in array access
WARNING: Further warnings have been suppressed.
This constraint, where there errors are referring to, contains a couple of strange things:
constraint
forall(i in 2..N-1,l in LIST, p in PAIR) (
if guest_at[i]=furious[i,first] then
guest_at[i+1]!=furious[i,second] /\
guest_at[i-1]!=furious[i,second]
else
true
endif
);
1) The second and third loop parameters l in List and p in PAIR is never used, so they are meaningless.
2) The main reason for the warning is that the furious matrix is just two rows, but in the loop variable i goes from 2 to 16. The error (array access out of bounds) indicates that when i is larger than 2 it's out of bound of the furious matrix.

SML: Basic Prime Testing

I'm trying to write a basic function to take an integer and evaluate to a bool that will check whether the integer is a prime or not.
I've used an auxiliary function to keep track of the current divisor I'm testing, like so:
fun is_divisible(n : int, currentDivisor : int) =
if currentDivisor <= n - 1 then
n mod currentDivisor = 0 orelse is_divisible(n, currentDivisor + 1)
else
true;
fun is_prime(n : int) : bool =
if n = 2 then
true
else
not(is_divisible(n, 2));
It looks right to me but I test it on 9 and get false and then on 11 and get false as well.
Sorry for all the questions today and thanks!
The problem is that if your is_divisible reaches the last case it should return false because it means that all the iterated divisors have resulted in a remainder larger than zero except for the last one which is the number it self. So you should rename is_divisible and return false instead of true

sqlite query - how do I get multiple results from a single row which is filtered by range?

I am quite new in programming and aspiring to make a game using cocos2dx and sqlite. But I came across this problem where I can't find an example on or how it can be done.
The first thing I want to do is to randomly select a row from a table which has been filtered by a range. For example there is a table with 100 rows. If I filter between the value 1 ~ 10 of Column D it resulted in 20 rows. From these 20 I want to randomly select one of them.
Secondly for that randomly selected row I want to collect 5 different value, but so far I was unable to find working example on how I can collect them.
Here is the code I try to come up with but is not working:
Query
int MinColumnD = 1;
int Max ColumnD = 10;
int Dice = ( rand() % 19 ) + 1;
char sql_query[100];
sprintf(sql_query, "SELECT A, B, C, D, E FROM SQList WHERE (ColumnD BETWEEN %d AND %d) ORDER BY RANDOM() LIMIT 1", MinColumnD, MaxColumnD);
std::list<INFO> details;
sqlite3_exec(DB, sql_query, CallBack, &details, &errorMessage);
*Thanks to CL's comment I updated the above query to include order by random() Limit 1. However when I run it and get to the section I get this error on xcode:
Thread 1
0 sqlite3_exec
0x54cbd8: movl 60(%ebx), %eax < Thread 1: EXC_BAD_ACCESS (code=1, address=0x444e418e)
This seems to only happen when I include the 'ORDER BY RANDOM()' as part of the query
Callback
int CallBack( void * pOutCount, int argc, char ** argv, char **azColName ){
std::list<Class::INFO> *pList = (std::list<Class::INFO >*)pOutCount;
Class::INFO items;
items._A = argv[0];
items._B = atoi(argv[1]);
items._C = atoi(argv[2]);
items._D = atoi(argv[3]);
items._E = atoi(argv[4]);
pList->push_back( items );
return 0;
}
Struct
struct Class::INFO {
std::string _A;
int _B;
int _C;
int _D;
int _E;
};
*Perhaps because the sqlite query is incomplete so I don't get the result properly but I am not sure how exactly I am able to get the returned list of values from the std::list. Is it correct to think that after the query then I can just call the component inside the list to get the value like:
std::string A = details._A;
int B = details._B;
int C = details._C;
int D = details._D;
int E = details._E;
Please help!
You do not know which rowids end up in the filtered result, so you cannot use them.
To get some random records from the filtered result, first order it randomly, then take the first record of that:
SELECT A, B, C, D, E
FROM SQList
WHERE ColumnD BETWEEN ? AND ?
ORDER BY RANDOM()
LIMIT 1

Resources