1 / 22

1 . Arrays and invariants

Learn how to manipulate arrays, initialize elements, and apply invariants effectively in Java programming. Covers array of objects, searching algorithms, selection ordering, and more.

amoss
Download Presentation

1 . Arrays and invariants

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 1.Arrays and invariants

  2. Arrays • An ordered collection of elements of the same type • Primitive types (int, double, char, boolean, .. • References to objects (Strings, …) • Size is determined at creation and cannot be modified

  3. X Arrays of primitive types int[] x;// equivalent toint x[] x = new int[3]; x[0] = 10; 10 x[1] = 20; 20 30 x[2] = 30; Note: x.lengthis a finalint variable with the size

  4. Referencias X Arrays of Objects Circle[] x; x = new Circle[3]; x[0] = new Circle(); x[1] = new Circle(); x[2] = new Circle();

  5. Arrays of Arrays • Java allows creating arrays of arrays using the following syntax int[][] m = new int[4][]; for (inti = 0; i < m.length; i++) { ma[i] = new int[i+1]; for (int j = 0; j < m[i].length; j++) { m[i][j] = i + j; } }

  6. Arreglos de Strings • Paso de parámetros Static public void main(String[] args) { for (inti = 0; i < args.length; i++) { System.out.println(″Argumento ″+(i+1)+ ″ = ″+args[i]); } }

  7. Initializing Arrays • Syntax for initializing arrays: boolean[] respuestas = {true, false, true}; String[] nombres = {"Ana María", "Carlos"}; String[][] geography = { { “Asia", “Japan“, “China”}, { “America“, “USA”, “Canada”, “Brazil”,”Mexico” }, { “Europe", “Germany", “Poland", “Belgium" } };

  8. Example: Searchingfortheindex of thebiggestnumber: Invariant Strategy: passtrhoughallelements a[0] to a[n-1] and registertheindex of thebiggestseen so far Invariant: a[m] = max(a[0] … a[k-1]), 1 <= k < n a0 a1 . . . ak-1 . . . an-1 ak m k staticintmindex(int[] a) { int m =0,k = 1; while(k <= a.length){ if (a[k] > a[m] ) m = k; k++ return m; }

  9. Theinvariant of aniteration • Invariant: A set of conditionsdescribingthestrategy • Frequentlyused to explainwhataniterationdoes • Alsoforformallyprovethattheiterationachieveswhatitshould • Should be true at beforebeginningtheiteration (while, for), duringtheiteration and afterendingit • Theinvariant and thenegation of theiterationconditionshould describe theachievement of thetask

  10. Initial and final conditions a) At thebeginningwehaveseen no number, so we asume thefirstoneisthebiggestbydoingm = 0] and k = 1; and theinvariantholds a0 a0 a1 a1 . . . . . . ai ai . . . . . . an-1 an-1 k b) In order to achievethegoal k must be equal to n so thewhileshould stop whenk == n, orcontinuewhilek != n, ork < n k

  11. Insidethewhile c) In order to make k closer to n wemustincreaseitsvalue. Howerver, thismight break theinvariant . k++; Unlesswemakesurethatwhenweincreasethevalue of k by 1 thevalue of m stillpoints to thebiggestelement if (a[k] < m) m = a[k]; a0 a1 . . . ai ai+1 . . . an-1 k

  12. Anotherexample: orderingbyselection • Basedonselectingthebiggestamongthe (remaining) elements and putit at therightside of thearraybeforetheonewhichwas “selected” in thepreviousiteration. Theinvariant looks likethis: • a[i] < a[i+1] for i = k to n-1 • a[j] < a [i] with j = 0 to k-1, notsorted and allsmallerthan a[k]

  13. Initial and final conditions • Initial: make k = n, whichimplies: • a[i] < a[i+1] for i = n to n-1 sorted (no element) • a[j] < a [n] for j = 0 to n-1, notsorted • ¿More intuitive?: beforeenteringtheloopputthebiggest in n-1 and make k= n-1 • b) final: k = 1 (orwhile k >= 2) • a[i] < a[i+1] for i = 1 to n-1 • a[j] < a [1] for j = 0 to 0, notsortedbutsmaller tan a[1]

  14. Program // sort a[0], ..., a[n-1] by selection k = n; // initially all n elemnts are not sorted while( k>1 )  { --k; //bring k closer to the goal, invariant may not hold bring the max of a[0], ..., a[k] to a[k]; //invariant is fixed   } Where bring the max of a[0], ..., a[k] to a[k]; => i = 0; // a[i] is the biggest so far for( j=1; j<=k; ++j )     if( a[j]>a[i] ) i = j; // now we exchange a[i] with a[k] t = a[i]; a[i] = a[k]; a[k] = t;

  15. Anotherexample Wehaveanarray a[0] . . . a[n-1] withintegers (positive and negatives) and wewant to putallthenumbers <=0 at theleft (notsorted) and thenumbers > 0 a theright. Thefrstoneis =0 Lets use thefollowinginvariant: allelementsuntil a[i] (included) are <=0, allelementsfrom a[i+1] to a[j-1] are >0, froma[j] on are unknown <= 0 > 0 unknown j i

  16. Initial and final situations == 0 unknown j i i = 0; j = 2 <= 0 > 0 i j j == n i dependsonthenumber of elements <=0

  17. Bringing j to n If a[j] <= 0 weincrementonly j, elsewe Exchange a[i] with a[j] and weincrement j and i <= 0 > 0 unknown j i staticint divide(int[] a) { int i=0,j = 1; while(k < a.length){ if (a[j] <=0 ) { intaux = a[i+1]; a[i+1] = a[j]; a[j]= aux; i++; } j++ } return m; }

  18. Evenharder to undertandwithoutinvariant Wehaveanarraywith n elements(a[0] … a[n-1]) blue and White unsorted. Leavetheelementsinterleved (one blue, one White …). Ifthere are more elementsfromone color tan anotherleavetheremainding of thesame color at theend. Assumethat at thebeginningwehaveone blue followedbytwo White elements Example, ifinicialywehave At theendtheyshould be in thefollowing positions invariante ??????????? i j

  19. Ejemplo 4: Explicar un algoritmo difícil (cont.) Inicialmente se hace i = 1; j = 3; final: j = n => continuaction : while (j < n) Restablecer el invariante j i j i ?????????? i j Si a[j] mismo color que a[i] no se hace nada, si no, se intercambia con a[i+1]; j++

  20. Ejemplo 4: Xn Cuando n es entero se puede programar una función más eficiente que la que usa java, basada en el cálculo de una serie. publicstaticdoublepower(double x, int n) { // Algoritmo simple int y = 1; for( int j=n; j>0; --j )     y = y*x; return y; } algoritmo O(n), y su invariante se puede escribir como y * xj == xn

  21. Aprovechando el invariante para la eficiencia Es posible encontrar un algoritmo sustancialmente más eficiente de la siguiente manera. publicstaticdoublepower(double x, int n) { intj = n; long z = x; int contador = 0; while (j>1) { if(j%2 == 0){ z = z*z; j = j/2; } else { z = x*z; j = j-1; } } System.out.println(“Resultado = "+z); } con invariante z* xj== xn

  22. Algoritmo algo más eficiente aún Sacando x del invariante publicstaticdoublepower(double x, int n) { int y = 1, z = x; for( int j=n; j>0; --j ) { while( j%2 == 0) {        z = z*z;         j = j/2;     }     y = y*z;  } Con invariante y * zj = xn

More Related