Introduction to Computer Science - Exercise 6

Name: Saggi Mizrahi • ID: 032493124 • Group: מעוף א'Date: November 26, 2013


Arrays

1ב.

No

1ב.

3.

Code:

/* arrmin.cpp
 * This program prints out the index where the longest decending sequnce of
 * numbers start.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>

using namespace std;

void readNumbers(int nums[], int max_numbers, int &out_size) {
    int num = 0;

    cin >> num;
    for (out_size = 0; out_size < max_numbers && num != -1; out_size++) {
        nums[out_size] = num;
        cin >> num;
    }
}

int descendingSequenceLength(int a[], int size) {
    int prevValue = a[0];
    int value;
    int i;

    for (i = 1; i < size; i++) {
        value = a[i];
        if (value >= prevValue) {
            break;
        }
        prevValue = value;
    }

    return i;
}

int longestDescendingSequenceIndex(int a[], int size) {
    int longestSequence = 0;
    int result = 0;
    int sequenceLength;
    int i = 0;

    while (size > longestSequence) {
        sequenceLength = descendingSequenceLength(&a[i], size);
        if (sequenceLength > longestSequence) {
            longestSequence = sequenceLength;
            result = i;
        }
        i += sequenceLength;
        size -= sequenceLength;
    }

    return result;
}

/* Prints out the index where the longest decending sequnce of descending
 * integers.
 *
 * Input: up to 50 numbers.
 * Output: the index where the longest decending sequnce of descending
 *         integers.
 */
int main()
{
    // declare constants
    const int SIZE = 50;

    // declare variables
    int nums[SIZE];
    int n = -1;

    // get user input
    cout << "please enter up to 50 numbers: ";
    readNumbers(nums, SIZE, n);

    // print out results
    cout << "Longest descending sequence starts at index " <<
        longestDescendingSequenceIndex(nums, n) << endl;
}

Outputs:

please enter up to 50 numbers: 5 3 1 4 6 4 3 2 -1 
Longest descending sequence starts at index 4

please enter up to 50 numbers: 1 2 3 4 5 -1 
Longest descending sequence starts at index 0

please enter up to 50 numbers: 5 4 3 2 1 21 20 -1 
Longest descending sequence starts at index 0

4.

Code:

/* oddeven.cpp
 *
 * Saggi Mizrahi 26 November 2013
 */
#include <iostream>

using namespace std;

void readNumbers(int nums[], int max_numbers, int &out_size);
void copyArray(int a[], int b[], int size);
void convertArray(int a[], double b[], int size);
int positiveNums(double a[], int size);
void positiveNums2(double a[], int size, int &res);
void copyOdd(int a[], int sizeA, int b[], int &sizeB);
void removeOdd(int a[], int &size);
void splitParity(int a[], int size);

void printArray(int a[], int size) {
    cout << "{";
    if (size > 0) {
        cout << a[0];
    }

    for (int i = 1; i < size; i++) {
        cout << ", " << a[i];
    }
    cout << "}";
}

void convertArray(int a[], double b[], int size) {
    for (int i = 0; i < size; i++) {
        b[i] = a[i];
    }
}

void copyArray(int a[], int b[], int size) {
    for (int i = 0; i < size; i++) {
        b[i] = a[i];
    }
}

void readNumbers(int nums[], int max_numbers, int &out_size) {
    int num = 0;

    cin >> num;
    for (out_size = 0; out_size < max_numbers && num != -1; out_size++) {
        nums[out_size] = num;
        cin >> num;
    }
}

int positiveNums(double a[], int size) {
    int count = 0;
    for (int i = 0; i < size; i++) {
        if (a > 0) {
            count++;
        }
    }

    return count;
}

void positiveNums2(double a[], int size, int &res) {
    res = positiveNums(a, size);
}

void copyOdd(int a[], int sizeA, int b[], int &sizeB) {
    int value;
    sizeB = 0;
    for (int i = 0; i < sizeA; i++) {
        value = a[i];
        if ((value % 2) != 0) {
            b[sizeB] = value;
            sizeB++;
        }
    }
}

void removeOdd(int a[], int &size) {
    int value;
    int i = 0;
    int j = 0;
    int n = size;

    while (j < n) {
        value = a[j];

        if ((value % 2) != 0) {
            j++;
            size--;
        } else {
            a[i] = a[j];
            i++;
            j++;
        }
    }
}

void splitParity(int a[], int size) {
    int i = 0;
    int j = size - 1;
    int tmp;
    while (i < j) {
        if ((a[i] % 2) == 0) {
            i++;
        } else if ((a[j] % 2) != 0) {
            j--;
        } else {
            tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;

            i++;
            j--;
        }
    }
}

int main()
{
    // declare constants
    const int SIZE = 50;

    // declare variables
    int nums[SIZE];
    double numsd[SIZE];
    int target[SIZE];
    int n = -1;
    int targetN = -1;

    // get user input
    cout << "please enter up to 50 numbers: ";
    readNumbers(nums, SIZE, n);

    // print out results
    convertArray(nums, numsd, n);
    cout << "There are " << positiveNums(numsd, n) <<
        " positiveNumbers" << endl;

    copyOdd(nums, n, target, targetN);
    cout << "There are " << targetN << " odd number" << endl;
    cout << "The odd numbers are: ";
    printArray(target, targetN);
    cout << endl;

    copyArray(nums, target, n);
    targetN = n;
    removeOdd(target, targetN);
    cout << "There are " << targetN << " even numbers" << endl;
    cout << "The even numbers are: ";
    printArray(target, targetN);
    cout << endl;

    splitParity(nums, n);
    cout << "Sorted by parity: ";
    printArray(nums, n);
    cout << endl;
}

Outputs:

please enter up to 50 numbers: 5 3 1 4 6 4 3 2 -1 
There are 8 positiveNumbers
There are 4 odd number
The odd numbers are: {5, 3, 1, 3}
There are 4 even numbers
The even numbers are: {4, 6, 4, 2}
Sorted by parity: {2, 4, 6, 4, 1, 3, 3, 5}

please enter up to 50 numbers: 1 2 3 4 5 -1 
There are 5 positiveNumbers
There are 3 odd number
The odd numbers are: {1, 3, 5}
There are 2 even numbers
The even numbers are: {2, 4}
Sorted by parity: {4, 2, 3, 1, 5}

please enter up to 50 numbers: 5 4 3 2 1 21 20 -1 
There are 7 positiveNumbers
There are 4 odd number
The odd numbers are: {5, 3, 1, 21}
There are 3 even numbers
The even numbers are: {4, 2, 20}
Sorted by parity: {20, 4, 2, 3, 1, 21, 5}

5.

Code:

/* matrix.cpp
 *
 * Saggi Mizrahi 26 November 2013
 */
#include <iostream>

using namespace std;

const int SIZE = 5;


double MeanMatrix(double a[][SIZE], int num_rows, int num_cols);
void MeanDiagonal(double a[][SIZE], int dim, double& diag1, double &diag2);
int positive(double A[][SIZE], int num_rows, int num_cols);


double MeanMatrix(double a[][SIZE], int num_rows, int num_cols) {
    double sum = 0;
    for (int y = 0; y < num_rows; y++) {
        for (int x = 0; x < num_cols; x++) {
            sum += a[y][x];
        }
    }

    return sum / (num_rows * num_cols);
}

void MeanDiagonal(double a[][SIZE], int dim, double& diag1, double &diag2) {
    diag1 = diag2 = 0;
    for (int i = 0; i < dim; i++) {
        diag1 += a[i][i];
        diag2 += a[i][dim - i - 1];
    }

    diag1 /= dim;
    diag2 /= dim;
}

int positive(double a[][SIZE], int num_rows, int num_cols) {
    int positiveN = 0;
    for (int y = 0; y < num_rows; y++) {
        for (int x = 0; x < num_cols; x++) {
            if (a[y][x] > 0) {
                positiveN++;
            }
        }
    }

    return positiveN;
}


int main()
{
    // declare constants
    // can't really used const since we have not yet learned about const
    // parameters so I can't pass a const to a method without the compiler
    // getting angry.
    /*const*/ double TEST[SIZE][SIZE] = {{0, 1, 2, 3, 4},
                                         {1, 2, 3, 4, 0},
                                         {2, 3, 4, 0, 1},
                                         {3, 4, 0, 1, 2},
                                         {4, 0, 1, 2, 3}};


    // declare variables
    double diag1, diag2;

    // output result
    cout << "Matrix Mean: " << MeanMatrix(TEST, SIZE, SIZE) << endl;

    MeanDiagonal(TEST, SIZE, diag1, diag2);
    cout << "Diagonal Means: " << diag1 << ", " << diag2 << endl;

    cout << "There are " << positive(TEST, SIZE, SIZE) <<
        " positive numbers in the matrix" << endl;
}

Outputs:

Matrix Mean: 2
Diagonal Means: 2, 4
There are 20 positive numbers in the matrix

6.

Code:

/* matrix.cpp
 *
 * Saggi Mizrahi 26 November 2013
 */
#include <iostream>

using namespace std;

const int SIZE = 5;

const char NULL_CHAR = '\0';
const char BRACKET_PAIRS[][2] = {{'{', '}'},
                                 {'(', ')'},
                                 {'[', ']'},
                                 {NULL_CHAR, NULL_CHAR}};

bool isOpener(char c) {
    for (int i = 0; BRACKET_PAIRS[i][0]; i++) {
        if (c == BRACKET_PAIRS[i][0]) {
            return true;
        }
    }

    return false;
}

bool isCloser(char c) {
    for (int i = 0; BRACKET_PAIRS[i][0]; i++) {
        if (c == BRACKET_PAIRS[i][1]) {
            return true;
        }
    }

    return false;
}

char matchingBracket(char c) {
    for (int i = 0; BRACKET_PAIRS[i][0]; i++) {
        if (c == BRACKET_PAIRS[i][0]) {
            return BRACKET_PAIRS[i][1];
        }
    }

    return NULL_CHAR;
}

int main()
{
    const char EOS = '\n';
    const int MAX_DEPTH = 30;

    // daclare variables
    char c;
    char expectedClosers[MAX_DEPTH] = {};
    int i = -1;


    cout << "please enter some brackets: ";

    while ((c = cin.get()) != EOS) {
        if (isOpener(c)) {
            i++;
            expectedClosers[i] = matchingBracket(c);
        } else if (isCloser(c)) {
            if (i < 0) {
                cout << "Error, unexpected closer '" << c <<
                    "'" << endl;
            } else if (c != expectedClosers[i]) {
                cout << "Error, expected '" <<
                    expectedClosers[i] <<
                    "' but found '" << c << "'" << endl;
                return -1;
            } else {
                i--;
            }
        }
    }

    if (i >= 0) {
        cout << "Error, unexpected end of stream, expected '" <<
            expectedClosers[i] << "'" << endl;
        return -1;
    } else {
        cout << "Input is valid" << endl;
        return 0;
    }
}

Outputs:

please enter some brackets: (())
Input is valid

please enter some brackets: ()(){}
Input is valid

please enter some brackets: ([()])
Input is valid

please enter some brackets: ({}
Error, unexpected end of stream, expected ')'

please enter some brackets: ({)}
Error, expected '}' but found ')'

please enter some brackets: ([{()[]}]){()}
Input is valid

please enter some brackets: ({)}
Error, expected '}' but found ')'

7.

Code:

/* newgirl.cpp
 *
 * Saggi Mizrahi 26 November 2013
 */
#include <iostream>
#include <string.h>

using namespace std;

const int DIGIT_OFFSET = '0';
const char EOS = '\0';

int isPalindrome(char s[]);
void switchLetters(char s[]);
void removeChar(char s[], char ch);
int strStr(char s1[], char s2[]);
int string2Integer(char s[]);
int strlen(char s[]);
int startswith(char s1[], char s2[]);

int strlen(char s[]) {
    int i;
    for (i = 0; s[i] != EOS; i++);
    return i;
}

// returns true if the input string is a palindrome.
//
// Assuming N is the length of the string the function performs with
// efficiency 1.5N.
int isPalindrome(char s[]) {
    int n = strlen(s);
    int middle = n / 2;
    for (int i = 0; i < middle; i++) {
        if (s[i] != s[n - 1 - i]) {
            return false;
        }
    }

    return true;
}

// switches adjacent letters.
//
// Assuming N is the length of the string the function performs with efficiency
// of 0.5N;
void switchLetters(char s[]) {
    char tmp;
    for(int i = 0; s[i] != EOS and s[i + 1] != EOS; i += 2) {
        tmp = s[i];
        s[i] = s[i + 1];
        s[i + 1] = tmp;
    }
}

// removes a char from the string.
//
// Assuming N is the length of the string the function performs with efficiency
// of N;
void removeChar(char s[], char ch) {
    int j = 0;
    for (int i = 0; s[i] != EOS; i++) {
        if (s[i] != ch) {
            s[j] = s[i];
            j++;
        }
    }
    s[j] = EOS;
}

int startswith(char s1[], char s2[]) {
    int i;
    for (i = 0; s1[i] == s2[i] && s2[i] != EOS; i++);
    if (s2[i] == EOS) {
        return 0;
    } else {
        return s1[i] - s2[i];
    }
}

// find a string in a string.
//
// Assuming N is the length of s1 and M is the length of s2 the function
// performs with efficiency of NM;
int strStr(char s1[], char s2[]) {
    for (int i = 0; s1[i] != EOS; i++) {
        if (startswith(&s1[i], s2) == 0) {
            return i;
        }
    }

    return -1;
}

// convert a string to an integer
//
// Assuming N is the length of the string the function performs with efficiency
// of NM;
int string2Integer(char s[]) {
    int res = 0;
    for (int i = 0; s[i] != EOS; i++) {
        res *= 10;
        res += s[i] - DIGIT_OFFSET;
    }

    return res;
}


int main()
{
    // declare constants
    const int MAX_LINES = 101;
    const int MAX_LINE_LENGTH = 257;

    const char SPACE = ' ';
    // can't really used const since we have not yet learned about const
    // parameters so I can't pass a const to a method without the compiler
    // getting angry.
    /*const*/ char DELETION_WORD[] = " new ";

    // declare variables
    char input[MAX_LINES][MAX_LINE_LENGTH];
    int line;
    int j;

    // read input
    cout << "Enter lines: " << endl;
    for (line = 0; (!cin.getline(input[line], MAX_LINE_LENGTH).eof() &&
                    line < MAX_LINE_LENGTH); line++);

    removeChar(input[0], SPACE);
    if (!isPalindrome(input[1])) {
        switchLetters(input[1]);
    }

    cout << "The number on the 3rd line is: " <<
        string2Integer(input[2]) << endl;

    j = 3;
    for (int i = 3; i < line; i++) {
        if (strStr(input[i], DELETION_WORD) == -1) {
            strcpy(input[j], input[i]);
            j++;
        }
    }

    for (int i = 0; i < j; i++) {
        cout << input[i] << endl;
    }
}

Outputs:

Enter lines: 
Ground control to major Tom
Ground control to major Tom
123
Well I can’t wait to tell you all about her, all about my new girl
(he can’t wait to tell you about his new girl)
And I can’t wait for you to hear me shout it, all about my new girl
(he can’t wait to tell you about his new girl)
When we were together you tried to break my heart
Said you always did your best at keeping us apart
Said now you’re dead and gone and I’ve got a new thing going...
I can’t wait to see your face when you and your friends show up Listen

The number on the 3rd line is: 123
GroundcontroltomajorTom
rGuodnc nortlot  oamoj roTm
123
When we were together you tried to break my heart
Said you always did your best at keeping us apart
I can’t wait to see your face when you and your friends show up Listen

8.

Code:

/* insort.cpp
 *
 * Saggi Mizrahi 26 November 2013
 */
#include <iostream>

using namespace std;

void insertionSort(int a[], int size);
void swap(int a[], int i1, int i2);
void readArray(int a[], int size);
void printArray(int a[], int size);


void swap(int a[], int i1, int i2) {
    int tmp = a[i1];
    a[i1] = a[i2];
    a[i2] = tmp;
}

void insertionSort(int a[], int size) {
    for (int n = 1; n < size; n++) {
        for (int i = n; i > 0 && a[i] < a[i - 1]; i--) {
            swap(a, i, i - 1);
        }
    }
}

void readArray(int a[], int size) {
    int tmp;
    for (int i = 0; i < size; i++) {
        cin >> tmp;
        a[i] = tmp;
    }
}

void printArray(int a[], int size) {
    cout << "{";
    if (size > 0) {
        cout << a[0];
    }

    for (int i = 1; i < size; i++) {
        cout << ", " << a[i];
    }
    cout << "}";
}

int main()
{
    // declare constants
    const int SIZE = 5;

    // declare variables
    int a[SIZE] = {};

    // get input
    cout << "please enter " << SIZE << " numbers: ";
    readArray(a, SIZE);

    // sort
    insertionSort(a, SIZE);

    // print sorted array
    printArray(a, SIZE);
    cout << endl;
}

Outputs:

please enter 5 numbers: 2 1 8 -4 2
{-4, 1, 2, 2, 8}

Complexity:

Complexity is {n(n+1)}\over{2}.

This is because we go 1 + 2 + 3 + 4 + ... + n which is known to amount to said calculation.

9.

Code:

/* spaceoddity.cpp
 *
 * Saggi Mizrahi 26 November 2013
 */
#include <iostream>

using namespace std;

int findChange(int arr[], int n);
void readArray(int a[], int size);

void readArray(int a[], int size) {
    int tmp;
    for (int i = 0; i < size; i++) {
        cin >> tmp;
        a[i] = tmp;
    }
}


int findChange(int arr[], int n) {
    int hop = n / 2. + 0.5;
    int i = hop - 1;
    while ((arr[i] % 2) != 0 || (arr[i + 1] % 2) == 0) {
        hop = hop / 2. + 0.5;
        i += (arr[i] % 2 == 0) ? hop : -hop;
    }
    if ((arr[i + 1] % 2) == 0) {
        i++;
    }
    return i;
}

int main()
{
    // declare constants
    const int SIZE = 100;

    // declare variables
    int a[SIZE] = {};
    int i;
    int n;

    // get input
    cout << "please enter how many numbers: ";
    cin >> n;
    cout << "please enter " << n << " numbers: ";
    readArray(a, n);

    // sort
    i = findChange(a, n);

    // print sorted array
    cout << i << ": " << a[i] << ", " << a[i + 1] << endl;
}

Outputs:

please enter how many numbers: 7
please enter 7 numbers: 2 4 8 7 5 4 3
2: 8, 7

please enter how many numbers: 7
please enter 7 numbers: 2 4 8 6 4 4 3
5: 4, 3

please enter how many numbers: 7
please enter 7 numbers: 2 4 8 6 4 3 3
4: 4, 3

please enter how many numbers: 7
please enter 7 numbers: 2 4 8 6 7 3 3
3: 6, 7

please enter how many numbers: 14
please enter 14 numbers: 2 4 8 6 7 3 3 2 41 213 3121 122 1 3 3
3: 6, 7