Lesson #13. Arrays (continuation)

Дата изменения: 23 ноября 2020

Theory

Lection in pdf format

Filling an array with generated sequence. lambda expressions

var a := Arr(1,3,5,7,9);   // [1,3,5,7,9] 
var a := ArrFill(5,555);  // [555,555,555,555,555] 
var a := Arr(55) * 4 + Arr(77) * 6;  // [55,55,55,55,77,77,77,77,77,77] 
var a := ArrGen(10,i->i);   // [0,1,2,3,4,5,6,7,8,9]
var a := ArrGen(10,i->i,1);  // [1,2,3,4,5,6,7,8,9,10] 
var a := ArrGen(10,1,x->x+2);  // [1,3,5,7,9,11,13,15,17,19] 
var a := ArrGen(10,1,x->x*2);  // [1,2,4,8,16,32,64,128,256,512]
var a := ArrGen(10,1,1,(x,y)->x+y);  // [1,1,2,3,5,8,13,21,34,55]

Array input and Randomly generated array

var a:=ReadArrInteger(5); 
var a:=ReadArrReal(5);
 
var a:=new integer[10];
a:=arrRandomInteger(10); // array of 10 generated integers from 0 to 99

Params keyword to pass a varying number of parameters

1
2
3
4
5
6
7
8
9
10
11
function Sum(params a: array of integer): integer;
begin
  Result := 0;
  foreach var x in a do
    Result += x;
end;
 
begin
  Print(Sum(1,3,5));
  Print(Sum(1,4,10,22,44));
end.
  • In the case of more than one parameter, params should be the last one in the list
  • SetLength procedure

  • Standard SetLength function allocates the necessary memory to contain the array elements
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    function MakeArr (params a: array of integer): array of integer;
    begin
      var b := new integer[a.length];
      var j := 0;
      for var i := 0 to a.length - 1 do 
        if a[i] > 0 then
        begin
          b[j] := a[i];
          j += 1;
        end;
      SetLength(b, j); // to specify a particular value of b array size
      result := b;
    end;
     
    begin
      var a := arrRandomInteger(5, -5, 10); // array a [-1,9,9,7,-3,0,-2,1,1,-1] 
      println('array a', a);
      println('result of function, array b ', MakeArr(a)); // array b  [9,9,7,1,1] 
    end.

    Reassignment and copy function

    var a: array of integer := (1,3,5,7); 
    var b:=a; // [1,3,5,7]

    But!

  • If we now reassign the values of the elements of the array b, then the array a will also change:
  • var a: array of integer := (1,3,5,7); 
    var b:=a; b[2]:=1; 
    print(a); //[1,3,1,7]
  • To avoid this situation, you need to create array b as a copy of array a:
  • var a: array of integer := (1,3,5,7); 
    var b:=Copy(a); 
    b[2]:=1; 
    print(a); //[1,3,5,7]

    Standard functions and procedures

    • Reverse(a)
    • Reverses elements in a array

    • a.IndexOf(x)
    • Finds the position (index) of x in a array

    • a.LastIndexOf(x)
    • Finds the last position (index) of x in a array

    • a.Contains(x)
    • Checks if the a array contains x

    Labs and tasks

    Filling an array with generated sequence

    {0.2 points} Task 1:

    To do: Generate an array of integers from -20 to 30. You should use ArrGen() function.

    The resulting example:

    [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3,
     -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
     22, 23, 24, 25, 26, 27, 28, 29, 30]
    

    [Program name: 13task-01.pas]

    {0.2 points} Task 2:

    To do: Generate an array of integers from -10 to 10 in increments of 2 (step = 2). You should use ArrGen() function.

    The resulting example:

    [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]
    

    [Program name: 13task-02.pas]

    {0.2 points} Task 3:

    To do: Generate an array of 20 numbers 5. You should use ArrFill() function.

    The resulting example:

    [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
    

    [Program name: 13task-03.pas]

    {0.2 points} Task 4:

    To do: Generate an array of the products of twos of numbers beginning with 1: i.e. 1 * 2, 2 * 2, 2 * 4, …). You should use ArrGen() function with two variables (x & y).

    The resulting example:

    [1,2,2,4,8,32,256,8192] 
    

    [Program name: 13task-04.pas]

    Params keyword. SetLength procedure

    Lab 1: Params keyword

    To do: Create a function to add any number of integers.

    ✍ Algorithm:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      
      function Sum(params a: array of integer): integer;
      begin
        Result := 0;
        foreach var x in a do
          Result += x;
      end;
       
      begin
        Print(Sum(1,3,5));
        Print(Sum(1,4,10,22,44));
      end.
    • params keyword is used to make it able to pass a varying number of parameters.
    • In the case of more than one parameter, params should be the last one in the list
    {0.4 points} Task 5:

    To do: Create a PrintArr procedure that prints out any number of parameters, delimited by a semicolon (there must be two parameters: array and delim). Use the default value for delim = '; '. Inside the main program, call the procedure several times with different number of parameters.

    Note: Procedure call example:

    var a:=new integer[10];
    a:=arrRandomInteger(10);
    PrintArr(';',a);
    PrintArr('~',1,2,3);
    // some more procedure call

    Extra task: * Correct the PrintArr procedure so that there is no delimeter after the last element.

    The resulting example:

    76 ; 22 ; 71 ; 92 ; 51 ; 68 ; 70 ; 47 ; 15 ; 37 ; 
    1 ~ 2 ~ 3 ~ 
    5 / 2 / 3 / 5 / 
    

    [Program name: 13task-05.pas]

    {0.4 points} Task 6:

    To do: An integer array is given. Write a procedure EvenDouble with one parameter: an integer array of any size. Procedure must double all the elements of the array with even values and print out the number of such elements.

    Note: Inside the main program, call the procedure several times with different number of parameters. Generate random array of different number of elements:

    var a := new integer[10];
    a := arrRandomInteger(5,-5,5);
    EvenDouble(a);
    // some more procedure calls

    The resulting example:

    the array before the task is done: [33,0,52,35,70,56,83,12,68,78] 
    result: 33 0 104 35 140 112 83 24 136 156 
    ---
    the array before the task is done: [5,-1,4,1,1] 
    result: 5 -1 8 1 1  
    

    [Program name: 13task-06.pas]

    Lab 2: SetLength

    To do: create a function to fill array b with positive numbers of array a

    ✍ Algorithm:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      
      function MakeOddArrFunc(params a: array of integer): array of integer;
      begin
        var b := new integer[a.length];
        var j := 0;
        for var i := 0 to a.length - 1 do 
          if a[i] > 0 then
          begin
            b[j] := a[i];
            j += 1;
          end;
        SetLength(b, j);
        result := b;
      end;
       
      begin
        var a := arrRandomInteger(10, -5, 10);
        println('array a', a);
        println('result of function, array b ', MakeOddArrFunc(a));
      end.
    {0.4 points} Task 7:

    To do: Create a function to fill array b with local minimums of array a. The local minimum is the element that is less than each of its neighbors. The first and last element should not be considered as local minima.

    The resulting example:

    array a [6,-2,3,-4,6] 
    result of function, array b  [-2,-4] 
    

    [Program name: 13task-07.pas]


    Standard functions and procedures and Transformation of an array elements

    Lab 3:

    To do: Create the function to search x in the array. The function returns -1 if it is not found and index of the element otherwise.

    ✍ Algorithm:

      function IndexOfW<T>(a: array of T; x: T): integer;
      begin
        var n := a.Length;
        var i := 0;
        while (i < n) and (a[i] <> x) do
          i += 1;
        Result := i = n ? -1 : i;
      end;
       
      begin
        var a := new integer[10];
        a := arrRandomInteger(10, 0, 10);
        print(a);
        print(indexOfW(a, 2))
      end.
    Lab 4:

    To do: Print out how many there odd elements are in the array.

    The resulting example:

    [18,10,91,47,35] 
    3 
    

    ✍ Algorithm:

      begin
        var a := new integer[5];
        a := arrRandomInteger(5); // [18,10,91,47,35] 
        print(a);
        print(a.Count(a->odd(a))) // 3 
      end.
    Lab 5:

    To do: Transform the array elements using the rule: if element is even then substruct it by 1, if it is odd then add 1 to it.

    ✍ Algorithm:

        begin
          var a := new integer[5];
          a := arrRandomInteger(5); // [4,36,93,36,29] 
          a.Transform(a,a -> a mod 2 = 0 ? a-1 : a + 1);
          print(a) // [3,35,94,35,30] 
        end.
    {0.5 points} Task 8:

    To do: Create a randomly generated array. Use the standard functions and procedures to implement the following goals. Print out:

    1. reversed array (Reverse())
    2. the position of x number (x is entered)
    3. the last position of x number (x is entered) (LastIndexOf())
    4. true if x exists in the array, false if it doesn’t (Contains())
    5. index of the first even element (IndexOf())
    6. the number of positive elements in the array (Count()). You should create your own function that returns true if the checked number is positive.
    7. maximum element and it’s index (Max(), IndexMax()).
    8. transformed array with a rule: if element is positive then square it, if it is negative then set it to 0 (Transform()).

    The resulting example:

    
    

    [Program name: 13task-08.pas]

    Lab 6, Loop over some indices:

    To do: Create an array of integer elements. Pint out the array values in the interval [10,19] and increase by one it’s positive values with even indexes.

    The resulting example:

    array: [41,90,100,12,16,7,69,23,59,37] 
    array values in the interval [10,19]: 12 16 
    

    ✍ Algorithm:

      begin
        var a:=arrRandomInteger(10);
        print(a);
        // values in the interval [10,19]
        foreach var i in a.Indices(x -> x.InRange(10,20)) do 
          print(a[i]);
       
        // positive values with even indexes
        foreach var i in a.Indices((x,i) -> (i mod 2 = 0) and (x > 0)) do 
          a[i] += 1;
      end.
    {0.4 points} Task 9:

    To do: Create a randomly generated array. Use loop over some indices to print out:

    • The values of the array with odd indexes.
    • The second half of the array elements.

    The resulting example:

    array: [8,41,56,82,8,93,44,70,6,54] 
    The second half of the array elements: 8 41 56 82 8 
    The values of the array with odd indexes: 41 82 93 70 54 
    

    [Program name: 13task-09.pas]

    Lab 7:

    To do: Create the procedure to shift circularly the elements to the left

    ✍ Algorithm:

      procedure CircularShiftLeft<T>(a: array of T);
      begin
        var v := a[0];
        for var i:=0 to a.Length-2 do
          a[i] := a[i+1];
        a[a.Length-1] := v;
      end;
       
      begin
        var a := new integer[5];
        a := arrRandomInteger(5); // [56,28,33,57,25] 
        CircularShiftLeft(a);
        print(a)// [28,33,57,25,56] 
      end.
    Lab 8:

    To do: Create the procedure to shift circularly the elements to the right

    ✍ Algorithm:

      procedure CircularShiftRight<T>(a: array of T);
      begin
        var v := a[a.Length-1];
        for var i:=a.Length-1 downto 1 do
          a[i] := a[i-1];
        a[0] := v;  
      end;
       
      begin
        var a := new integer[5];
        a := arrRandomInteger(5); // [25,23,74,17,31] 
        CircularShiftRight(a);
        print(a)// [31,25,23,74,17] 
      end.
    {0.3 points} Task 10:

    To do: Create a randomly generated array. At first, transform its elements using the rule: a-1, and after, reverse it’s elements and after, make a circular shift it’s elements to the right and to the left.

    The resulting example:

    array:  [93,25,52,74,76,40,54,13,29,65] 
    transformed:  [92,24,51,73,75,39,53,12,28,64] 
    Shift left:  [24,51,73,75,39,53,12,28,64,92] 
    Shift right:  [92,24,51,73,75,39,53,12,28,64] 
    

    [Program name: 13task-10.pas]

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    *
    *


    Вставить формулу как
    Блок
    Строка
    Дополнительные настройки
    Цвет формулы
    Цвет текста
    #333333
    Используйте LaTeX для набора формулы
    Предпросмотр
    \({}\)
    Формула не набрана
    Вставить