6.5 Exercises

  1. Using the array arr with value a[0] = 9, a[1] = 2, a[2] = 5, a[3] = 4, a[4] = 3, determine the output of the code in Example 6-11.

    Example 6-11. Code for Exercise 1
        1 i = 0
        2 
        3 while (i < a.size)
        4 	puts a[i]
        5 	i = i + 1
        6 end
    
  2. The code in Example 6-12 looks for the first two elements that are out of order and swaps them; however, it is not producing the correct results. Fix the code so that it works correctly.

    Example 6-12. Code for Exercise 2
        1 arr = [5, 22, 29, 39, 19, 51, 78, 96, 84]
        2 i = 0 
        3 while (i < arr.size - 1 and arr[i] < arr[i + 1])
        4     i = i + 1 
        5 end 
        6 puts i 
        7 
        8 arr[i] = arr[i + 1]
        9 arr[i + 1] = arr[i]
    
  3. Write a program that splits an array into two arrays where any element in one array is smaller than any element in the other array. Solutions are not unique, but equally sized splits are desirable. The input can be any size array less than 100.

    Example input: [6, 45, 23, 65, 17, 48, 97, 32, 18, 9, 88]

    Example output: [6, 23, 17, 18 , 9] < [45, 65, 48, 97, 32, 88]

  4. There are many ways to store image data. One way is to store pixel data in a two-dimensional array. The pixel data is itself a three-element array that describes the amount of red, green, and blue in the pixel. The amount of red, green, or blue is a number from 0 to 255. Here are a few example RGB values:

    red = [255, 0, 0]
    green = [0, 255, 0]
    blue = [0, 0, 255]
    black = [0, 0, 0]
    white = [255, 255, 255]
    yellow = [255, 255, 0]

    Suppose you have a picture and need to count red pixels. ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.