Friday, June 30, 2017

t1.c

#include<intarr.h>
#include<stdio.h>

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
  unsigned int length = ia->len;
  FILE* f = fopen(filename, "w");
  if(f == NULL){
    return 1;
  }
  // write the length header
  int hdr[1];
  hdr[0] = ia->len;

  if( fwrite(hdr, sizeof(intarr_t), 1, f) != 1){
    return 1;
  }

  if(fwrite(ia->data, sizeof(intarr_t),length, f) != length){
    return 1;
  }
  fclose(f);
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
  FILE* f = fopen(filename, "r");
  if(f == NULL){
    return NULL;
  }
  int hdr[1];
  if( fread(hdr, sizeof(intarr_t), 1, f) != 1){
    return 1;
  }

  intarr_t ia;
  ia->len = hdr[0];
  ia->data = malloc((ia->len)*sizeof(int));
  if(ia->len != 0){
    if(ia->data == NULL){
      return NULL;
    }
  }

  if(fread(ia->data, sizeof(intarr_t),length, f) != length){
    return NULL;
  }
  fclose(f);
  return ia;
}

Thursday, June 29, 2017

merge

int* mergeTwo(int arr1[], int arr2[], int len1, int len2)
{
  int j=0, k=0;
  int* newArr = malloc((len1+len2)*sizeof(int));
  int newLen = len1+len2;
  for(int i=0; i<newLen; i++){
    if(j<len1 && k<len2){
    if (arr1[j] <= arr2[k]){
              newArr[i] = arr1[j];
              j++;
    }else{
        newArr[i] = arr2[k];
        k++;
    }
    }else if(j>=len1){
      newArr[i]=arr2[k];
      k++;
    }else{
    newArr[i]=arr1[j];
    j++;
    }
  }
  return newArr;
}

Wednesday, June 28, 2017

intarr

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Structure type that encapsulates our safe int array. */
typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

/* A type for returning status codes */
typedef enum {
  INTARR_OK,
  INTARR_BADARRAY,
  INTARR_BADINDEX,
  INTARR_BADALLOC,
  INTARR_NOTFOUND
} intarr_result_t;

/* LAB 5 TASK 1 */

// Create a new intarr_t with initial size len.  If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated intarr_t.  If unsuccessful, returns a null pointer.
intarr_t* intarr_create( unsigned int len )
{
  intarr_t*pointer = malloc(sizeof(intarr_t));
  if (pointer == NULL){
      return NULL;
  }
  pointer->data = malloc(sizeof(unsigned int)*len);
  if(pointer->data == NULL){
    return NULL;
  }
  pointer->len = len;
  return pointer;
}

// frees all memory allocated for ia. If the pointer is null, do
// nothing. If the ia->data is null, do not attempt to free it.
void intarr_destroy( intarr_t* ia )
{
    if(ia->data != NULL){
        free(ia);
    }
}

/* LAB 5 TASK 2 */

// If index is valid, set the value at ia->data[index] to val and return
// INTARR_OK. Otherwise, leave the array unmodified and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_set( intarr_t* ia,
                unsigned int index,
                int val )
{
  unsigned int length = ia->len;
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index<length){
    ia->data[index] = val;
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

// If index is valid and i is non-null, set *i to ia->data[index] and return
// INTARR_OK. Otherwise no not modify *i and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_get( const intarr_t* ia,
                unsigned int index,
                int* i )
{
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index< ia->len){
    *i = ia->data[index];
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 3 */

// Return a duplicate of ia, allocating new storage for the duplicate
// data (we call this a "deep copy"). If unsuccessful (i.e. memory
// allocation for the copy fails, or ia is null), return a null pointer.
intarr_t* intarr_copy( const intarr_t* ia )
{
  if((ia->data ==NULL)|| ia == NULL){
    return NULL;
  }
  intarr_t* newArr = intarr_create(ia->len);
  newArr->len = ia->len;
  const unsigned int bytes = (ia->len)*sizeof(unsigned int);
  memcpy(newArr->data, ia->data, bytes);
  return newArr;
}

/* LAB 5 TASK 4 */

// sort ia by value smallest-to-largest, so that data[i] < data[i+1]
// for all valid i, then return INTARR_OK. Works in-place: contents of
// ia are sorted on return. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_sort( intarr_t* ia )
{
  if(ia == NULL){
    return INTARR_BADARRAY;
  }
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  for(int i=0; i< (ia->len)-1; i++){
    for(int k=i+1; k< ia->len; k++){
      if(ia->data[k]< ia->data[i]){
        int temp = ia->data[i];
        ia->data[i] = ia->data[k];
        ia->data[k] = temp;
      }
    }
  }
  return INTARR_OK;
}

/* LAB 5 TASK 5 */

// Find the first occurence of the target in the array, searching from
// index 0. If the target is found and i is non-null, set *i to the
// location index and return INTARR_OK. If target does not occur in
// the array, leave *i unmodified and return INTARR_NOTFOUND. If ia is
// null, return INTARR_BADARRAY.
intarr_result_t intarr_find( intarr_t* ia, int target, int* i )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  for(int k=0; k< ia->len; k++){
    if(ia->data[k] == target){
      *i = k;
      return INTARR_OK;
    }
  }
  return INTARR_NOTFOUND;
}

/* LAB 5 TASK 6 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_push( intarr_t* ia, int val )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  ia->data = realloc(ia->data, sizeof(int)*((ia->len)+1));
  if(ia == NULL|| ia->data == NULL){
    return INTARR_BADALLOC;
  }
  ia->data[(ia->len)] = val;
  return INTARR_OK;
}

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(ia->len != 0 || i != NULL){
    *i = ia->data[(ia->len)-1];
    ia->data = realloc(ia->data, sizeof(unsigned int)*((ia->len) -1));
    if(ia == NULL || ia->data == NULL){
       return INTARR_BADARRAY;
    }
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 7 */

// Resize ia to contain newlen values. If newlen is less than the
// original array length, the end of the array is discarded. If newlen
// is greater than the original array length, intialize all the new
// integers to zero. If the allocation is successful, return
// INTARR_OK, otherwise return INTARR_BADALLOC. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_resize( intarr_t* ia, unsigned int newlen )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  ia->data = realloc(ia->data, sizeof(int)*newlen);
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADALLOC;
  }
  if(ia->len < newlen){
    for(int i= ia->len ; i<newlen; i++){
      ia->data[i] = 0;
    }
  }
  return INTARR_OK;
}

/* LAB 5 TASK 8 */

// Get a deep copy of a portion of ia from index first to index last
// inclusive. If successful, return a pointer to a newly-allocated
// intarr_t containing a copy of the specfied section. If an error
// occurs, i.e. ia is null, first or last are out of bounds, last <
// first, or memory allocation fails, return a null pointer.
intarr_t* intarr_copy_subarray( intarr_t* ia,
                unsigned int first,
                unsigned int last )
{
  if(ia == NULL || ia->data == NULL){
    return NULL;
  }
  if(last<first){
    return NULL;
  }
  if(last>= ia->len || first>= ia->len){
    return NULL;
  }
  unsigned int newLen = last-first+1;
  intarr_t* newData = intarr_create(newLen);
  if(newData != NULL){
    for(int i=0; i<newLen; i++){
      newData->data[i]= ia->data[first+i];
    }
  }
  return newData;
}

/* LAB 5 ENDS HERE */

/* -------------------------------------------------------------- */

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
  return NULL;
}


/* LAB 6 TASK 2 */

/*
  Save the entire array ia into a file called 'filename' in a JSON
  text file array file format that can be loaded by
  intarr_load_json(). Returns zero on success, or a non-zero error
  code on failure. Arrays of length 0 should produce an output file
  containing an empty array.

  The JSON output should be human-readable.

  Examples:

  The following line is a valid JSON array:
  [ 100, 200, 300 ]

  The following lines are a valid JSON array:
  [
   100,
   200,
   300
  ]
*/
int intarr_save_json( intarr_t* ia, const char* filename )
{
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_json(). The file may contain an array
  of length 0. Returns a pointer to a newly-allocated intarr_t on
  success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename )
{
  return NULL;
}

Tuesday, June 27, 2017

intarr

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Structure type that encapsulates our safe int array. */
typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

/* A type for returning status codes */
typedef enum {
  INTARR_OK,
  INTARR_BADARRAY,
  INTARR_BADINDEX,
  INTARR_BADALLOC,
  INTARR_NOTFOUND
} intarr_result_t;

/* LAB 5 TASK 1 */

// Create a new intarr_t with initial size len.  If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated intarr_t.  If unsuccessful, returns a null pointer.
intarr_t* intarr_create( unsigned int len )
{
  intarr_t*pointer = malloc(sizeof(intarr_t));
  if (pointer == NULL){
      return NULL;
  }
  pointer->data = malloc(sizeof(unsigned int)*len);
  if(pointer->data == NULL){
    return NULL;
  }
  pointer->len = len;
  return pointer;
}

// frees all memory allocated for ia. If the pointer is null, do
// nothing. If the ia->data is null, do not attempt to free it.
void intarr_destroy( intarr_t* ia )
{
    if(ia->data != NULL){
        free(ia);
    }
}

/* LAB 5 TASK 2 */

// If index is valid, set the value at ia->data[index] to val and return
// INTARR_OK. Otherwise, leave the array unmodified and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_set( intarr_t* ia,
                unsigned int index,
                int val )
{
  unsigned int length = ia->len;
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index<length){
    ia->data[index] = val;
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

// If index is valid and i is non-null, set *i to ia->data[index] and return
// INTARR_OK. Otherwise no not modify *i and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_get( const intarr_t* ia,
                unsigned int index,
                int* i )
{
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index< ia->len){
    *i = ia->data[index];
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 3 */

// Return a duplicate of ia, allocating new storage for the duplicate
// data (we call this a "deep copy"). If unsuccessful (i.e. memory
// allocation for the copy fails, or ia is null), return a null pointer.
intarr_t* intarr_copy( const intarr_t* ia )
{
  if((ia->data ==NULL)|| ia == NULL){
    return NULL;
  }
  intarr_t* newArr = intarr_create(ia->len);
  newArr->len = ia->len;
  const unsigned int bytes = (ia->len)*sizeof(unsigned int);
  memcpy(newArr->data, ia->data, bytes);
  return newArr;
}

/* LAB 5 TASK 4 */

// sort ia by value smallest-to-largest, so that data[i] < data[i+1]
// for all valid i, then return INTARR_OK. Works in-place: contents of
// ia are sorted on return. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_sort( intarr_t* ia )
{
  if(ia == NULL){
    return INTARR_BADARRAY;
  }
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  for(int i=0; i< (ia->len)-1; i++){
    for(int k=i+1; k< ia->len; k++){
      if(ia->data[k]< ia->data[i]){
        int temp = ia->data[i];
        ia->data[i] = ia->data[k];
        ia->data[k] = temp;
      }
    }
  }
  return INTARR_OK;
}

/* LAB 5 TASK 5 */

// Find the first occurence of the target in the array, searching from
// index 0. If the target is found and i is non-null, set *i to the
// location index and return INTARR_OK. If target does not occur in
// the array, leave *i unmodified and return INTARR_NOTFOUND. If ia is
// null, return INTARR_BADARRAY.
intarr_result_t intarr_find( intarr_t* ia, int target, int* i )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  for(int k=0; k< ia->len; k++){
    if(ia->data[k] == target){
      *i = k;
      return INTARR_OK;
    }
  }
  return INTARR_NOTFOUND;
}

/* LAB 5 TASK 6 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_push( intarr_t* ia, int val )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  ia = realloc(ia->data, sizeof(int)*((ia->len)+1));
  if(ia == NULL|| ia->data == NULL){
    return INTARR_BADALLOC;
  }
  ia->data[(ia->len)] = val;
  return INTARR_OK;
}

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(ia->len != 0){
    ia->data[(ia->len)-1] = *i;
    ia = realloc(ia->data, sizeof(unsigned int)*(len-1));
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 7 */

// Resize ia to contain newlen values. If newlen is less than the
// original array length, the end of the array is discarded. If newlen
// is greater than the original array length, intialize all the new
// integers to zero. If the allocation is successful, return
// INTARR_OK, otherwise return INTARR_BADALLOC. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_resize( intarr_t* ia, unsigned int newlen )
{
  if(ia == NULL || ia->data == NULL || ia->len ==0){
    return INTARR_BADARRAY;
  }
  ia = realloc(ia->data, sizeof(int)*newlen);
  if(ia == NULL){
    return INTARR_BADALLOC;
  }
  if(ia->len < newlen){
    for(int i= ia->len ; i<newlen; i++){
      ia->data[i] = 0;
    }
  }
  return INTARR_OK;
}

/* LAB 5 TASK 8 */

// Get a deep copy of a portion of ia from index first to index last
// inclusive. If successful, return a pointer to a newly-allocated
// intarr_t containing a copy of the specfied section. If an error
// occurs, i.e. ia is null, first or last are out of bounds, last <
// first, or memory allocation fails, return a null pointer.
intarr_t* intarr_copy_subarray( intarr_t* ia,
                unsigned int first,
                unsigned int last )
{
  if(ia == NULL || ia->data == NULL){
    return NULL;
  }
  if(last<first){
    return NULL;
  }
  if(last>= ia->len || first>= ia->len){
    return NULL;
  }
  unsigned int newLen = last-first+1;
  intarr_t* newData = intarr_create(newLen);
  if(newData != NULL){
    for(int i=0; i<newLen; i++){
      newData->data[i]= ia->data[first+i];
    }
  }
  return newData;
}

/* LAB 5 ENDS HERE */

/* -------------------------------------------------------------- */

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
  return NULL;
}


/* LAB 6 TASK 2 */

/*
  Save the entire array ia into a file called 'filename' in a JSON
  text file array file format that can be loaded by
  intarr_load_json(). Returns zero on success, or a non-zero error
  code on failure. Arrays of length 0 should produce an output file
  containing an empty array.

  The JSON output should be human-readable.

  Examples:

  The following line is a valid JSON array:
  [ 100, 200, 300 ]

  The following lines are a valid JSON array:
  [
   100,
   200,
   300
  ]
*/
int intarr_save_json( intarr_t* ia, const char* filename )
{
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_json(). The file may contain an array
  of length 0. Returns a pointer to a newly-allocated intarr_t on
  success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename )
{
  return NULL;
}

int main()
{
    return 0;
}

stack overflow

question 2:

 #include<stdlib.h>
#include<stdio.h>
#include<assert.h>

void overflow(int n)
{
  if(n == INT_MAX){
    return;
  }
  printf("%d\n",n);
  overflow(n+1);
}


void foo(int n)
{
    int* arr = malloc(100*sizeof(int));
    assert(arr);
    for(int i=0; i<100; i++){
        arr[i] = i+n;
    }
    printf("%d\n", arr[99]);
    foo(n+1);
}

void bar(int n)
{
    int arr[100];
    for(int i=0; i<100;i++){
        arr[i] = i+n;
    }
    printf("%d\n",arr[99]);
    bar(n+1);
}

int main()
{
  bar(1);
  return 0;
}


b)
c)
using foo:

using bar:

intarr

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Structure type that encapsulates our safe int array. */
typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

/* A type for returning status codes */
typedef enum {
  INTARR_OK,
  INTARR_BADARRAY,
  INTARR_BADINDEX,
  INTARR_BADALLOC,
  INTARR_NOTFOUND
} intarr_result_t;

/* LAB 5 TASK 1 */

// Create a new intarr_t with initial size len.  If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated intarr_t.  If unsuccessful, returns a null pointer.
intarr_t* intarr_create( unsigned int len )
{
  intarr_t*pointer = malloc(sizeof(intarr_t));
  if (pointer == NULL){
      return NULL;
  }
  pointer->data = malloc(sizeof(unsigned int)*len);
  if(pointer->data == NULL){
    return NULL;
  }
  pointer->len = len;
  return pointer;
}

// frees all memory allocated for ia. If the pointer is null, do
// nothing. If the ia->data is null, do not attempt to free it.
void intarr_destroy( intarr_t* ia )
{
    if(ia->data != NULL){
        free(ia);
    }
}

/* LAB 5 TASK 2 */

// If index is valid, set the value at ia->data[index] to val and return
// INTARR_OK. Otherwise, leave the array unmodified and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_set( intarr_t* ia,
                unsigned int index,
                int val )
{
  unsigned int length = ia->len;
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index<length){
    ia->data[index] = val;
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

// If index is valid and i is non-null, set *i to ia->data[index] and return
// INTARR_OK. Otherwise no not modify *i and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_get( const intarr_t* ia,
                unsigned int index,
                int* i )
{
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index< ia->len){
    *i = ia->data[index];
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 3 */

// Return a duplicate of ia, allocating new storage for the duplicate
// data (we call this a "deep copy"). If unsuccessful (i.e. memory
// allocation for the copy fails, or ia is null), return a null pointer.
intarr_t* intarr_copy( const intarr_t* ia )
{
  if((ia->data ==NULL)|| ia == NULL){
    return NULL;
  }
  intarr_t* newArr = intarr_create(ia->len);
  newArr->len = ia->len;
  const unsigned int bytes = (ia->len)*sizeof(unsigned int);
  memcpy(newArr->data, ia->data, bytes);
  return newArr;
}

/* LAB 5 TASK 4 */

// sort ia by value smallest-to-largest, so that data[i] < data[i+1]
// for all valid i, then return INTARR_OK. Works in-place: contents of
// ia are sorted on return. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_sort( intarr_t* ia )
{
  if(ia == NULL){
    return INTARR_BADARRAY;
  }
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  for(int i=0; i< (ia->len)-1; i++){
    for(int k=i+1; k< ia->len; k++){
      if(ia->data[k]< ia->data[i]){
        int temp = ia->data[i];
        ia->data[i] = ia->data[k];
        ia->data[k] = temp;
      }
    }
  }
  return INTARR_OK;
}

/* LAB 5 TASK 5 */

// Find the first occurence of the target in the array, searching from
// index 0. If the target is found and i is non-null, set *i to the
// location index and return INTARR_OK. If target does not occur in
// the array, leave *i unmodified and return INTARR_NOTFOUND. If ia is
// null, return INTARR_BADARRAY.
intarr_result_t intarr_find( intarr_t* ia, int target, int* i )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  for(int k=0; k< ia->len; k++){
    if(ia->data[k] == target){
      *i = k;
      return INTARR_OK;
    }
  }
  return INTARR_NOTFOUND;
}

/* LAB 5 TASK 6 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_push( intarr_t* ia, int val )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  ia = realloc(ia->data, sizeof(int)*(ia->len+1));
  ia->data[ia->len] = val;
  if(ia == NULL|| ia->data == NULL){
    return INTARR_BADALLOC;
  }
  return INTARR_OK;
}

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(ia->len != 0){
    ia->data[(ia->len)-1] = *i;
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 7 */

// Resize ia to contain newlen values. If newlen is less than the
// original array length, the end of the array is discarded. If newlen
// is greater than the original array length, intialize all the new
// integers to zero. If the allocation is successful, return
// INTARR_OK, otherwise return INTARR_BADALLOC. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_resize( intarr_t* ia, unsigned int newlen )
{
  if(ia == NULL || ia->data == NULL){
    return INTARR_BADARRAY;
  }
  ia = realloc(ia->data, sizeof(int)*newlen);
  if(ia == NULL){
    return INTARR_BADALLOC;
  }
  if(ia->len < newlen){
    for(int i= ia->len ; i<newlen; i++){
      ia->data[i] = 0;
    }
  }
  return INTARR_OK;
}

/* LAB 5 TASK 8 */

// Get a deep copy of a portion of ia from index first to index last
// inclusive. If successful, return a pointer to a newly-allocated
// intarr_t containing a copy of the specfied section. If an error
// occurs, i.e. ia is null, first or last are out of bounds, last <
// first, or memory allocation fails, return a null pointer.
intarr_t* intarr_copy_subarray( intarr_t* ia,
                unsigned int first,
                unsigned int last )
{
  if(ia == NULL || ia->data == NULL){
    return NULL;
  }
  if(last<first){
    return NULL;
  }
  if(last>= ia->len || first>= ia->len){
    return NULL;
  }
  unsigned int newLen = last-first+1;
  intarr_t* newData = intarr_create(newLen);
  if(newData != NULL){
    for(int i=0; i<newLen; i++){
      newData->data[i]= ia->data[first+i];
    }
  }
  return newData;
}

/* LAB 5 ENDS HERE */

/* -------------------------------------------------------------- */

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
  return NULL;
}


/* LAB 6 TASK 2 */

/*
  Save the entire array ia into a file called 'filename' in a JSON
  text file array file format that can be loaded by
  intarr_load_json(). Returns zero on success, or a non-zero error
  code on failure. Arrays of length 0 should produce an output file
  containing an empty array.

  The JSON output should be human-readable.

  Examples:

  The following line is a valid JSON array:
  [ 100, 200, 300 ]

  The following lines are a valid JSON array:
  [
   100,
   200,
   300
  ]
*/
int intarr_save_json( intarr_t* ia, const char* filename )
{
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_json(). The file may contain an array
  of length 0. Returns a pointer to a newly-allocated intarr_t on
  success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename )
{
  return NULL;
}

int main()
{
    return 0;
}

Monday, June 26, 2017

intarr

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Structure type that encapsulates our safe int array. */
typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

/* A type for returning status codes */
typedef enum {
  INTARR_OK,
  INTARR_BADARRAY,
  INTARR_BADINDEX,
  INTARR_BADALLOC,
  INTARR_NOTFOUND
} intarr_result_t;

/* LAB 5 TASK 1 */

// Create a new intarr_t with initial size len.  If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated intarr_t.  If unsuccessful, returns a null pointer.
intarr_t* intarr_create( unsigned int len )
{
    intarr_t*pointer = malloc(sizeof(intarr_t));
    if (pointer == NULL){
        return NULL;
    }
    pointer->data = malloc(sizeof(unsigned int)*len);
    if(pointer == NULL){
      return NULL;
    }
    pointer->len = len;
    return pointer;
}

// frees all memory allocated for ia. If the pointer is null, do
// nothing. If the ia->data is null, do not attempt to free it.
void intarr_destroy( intarr_t* ia )
{
    if(ia->data != NULL){
        free(ia);
    }
}

/* LAB 5 TASK 2 */

// If index is valid, set the value at ia->data[index] to val and return
// INTARR_OK. Otherwise, leave the array unmodified and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_set( intarr_t* ia,
                unsigned int index,
                int val )
{
  unsigned int length = ia->len;
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index<length){
    ia->data[index] = val;
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

// If index is valid and i is non-null, set *i to ia->data[index] and return
// INTARR_OK. Otherwise no not modify *i and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_get( const intarr_t* ia,
                unsigned int index,
                int* i )
{
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index< ia->len){
    i = &(ia->data[index]);
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 3 */

// Return a duplicate of ia, allocating new storage for the duplicate
// data (we call this a "deep copy"). If unsuccessful (i.e. memory
// allocation for the copy fails, or ia is null), return a null pointer.
intarr_t* intarr_copy( const intarr_t* ia )
{
  if(ia->data ==NULL){
    return NULL;
  }
  intarr_t* newArr = malloc(sizeof(intarr_t));
  if(newArr == NULL){
    return NULL;
  }
  newArr->data = malloc();
  newArr->len = ia->len;
  return newArr;
}

/* LAB 5 TASK 4 */

// sort ia by value smallest-to-largest, so that data[i] < data[i+1]
// for all valid i, then return INTARR_OK. Works in-place: contents of
// ia are sorted on return. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_sort( intarr_t* ia )
{
}

/* LAB 5 TASK 5 */

// Find the first occurence of the target in the array, searching from
// index 0. If the target is found and i is non-null, set *i to the
// location index and return INTARR_OK. If target does not occur in
// the array, leave *i unmodified and return INTARR_NOTFOUND. If ia is
// null, return INTARR_BADARRAY.
intarr_result_t intarr_find( intarr_t* ia, int target, int* i )
{
}

/* LAB 5 TASK 6 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_push( intarr_t* ia, int val )
{
}

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
}

/* LAB 5 TASK 7 */

// Resize ia to contain newlen values. If newlen is less than the
// original array length, the end of the array is discarded. If newlen
// is greater than the original array length, intialize all the new
// integers to zero. If the allocation is successful, return
// INTARR_OK, otherwise return INTARR_BADALLOC. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_resize( intarr_t* ia, unsigned int newlen )
{
}

/* LAB 5 TASK 8 */

// Get a deep copy of a portion of ia from index first to index last
// inclusive. If successful, return a pointer to a newly-allocated
// intarr_t containing a copy of the specfied section. If an error
// occurs, i.e. ia is null, first or last are out of bounds, last <
// first, or memory allocation fails, return a null pointer.
intarr_t* intarr_copy_subarray( intarr_t* ia,
                unsigned int first,
                unsigned int last )
{
}

/* LAB 5 ENDS HERE */

/* -------------------------------------------------------------- */

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
}


/* LAB 6 TASK 2 */

/*
  Save the entire array ia into a file called 'filename' in a JSON
  text file array file format that can be loaded by
  intarr_load_json(). Returns zero on success, or a non-zero error
  code on failure. Arrays of length 0 should produce an output file
  containing an empty array.

  The JSON output should be human-readable.

  Examples:

  The following line is a valid JSON array:
  [ 100, 200, 300 ]

  The following lines are a valid JSON array:
  [
   100,
   200,
   300
  ]
*/
int intarr_save_json( intarr_t* ia, const char* filename )
{
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_json(). The file may contain an array
  of length 0. Returns a pointer to a newly-allocated intarr_t on
  success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename )
{
}

stackoverflow

#include<limits.h>
#include<stdio.h>

void overflow(int n)
{
  if(n == INT_MAX){
    return;
  }
  printf("%d",n);
  n= overflow(n+1);
}

int main()
{
  overflow(1);
  return 0;
}

intarr

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Structure type that encapsulates our safe int array. */
typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

/* A type for returning status codes */
typedef enum {
  INTARR_OK,
  INTARR_BADARRAY,
  INTARR_BADINDEX,
  INTARR_BADALLOC,
  INTARR_NOTFOUND
} intarr_result_t;

/* LAB 5 TASK 1 */

// Create a new intarr_t with initial size len.  If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated intarr_t.  If unsuccessful, returns a null pointer.
intarr_t* intarr_create( unsigned int len )
{
    intarr_t*pointer = malloc(sizeof(unsigned int)*len);
    if (pointer == NULL){
        return NULL;
    }
    return pointer;
}

// frees all memory allocated for ia. If the pointer is null, do
// nothing. If the ia->data is null, do not attempt to free it.
void intarr_destroy( intarr_t* ia )
{
    if(ia->data != NULL){
        free(ia);
    }
}

/* LAB 5 TASK 2 */

// If index is valid, set the value at ia->data[index] to val and return
// INTARR_OK. Otherwise, leave the array unmodified and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_set( intarr_t* ia,
                unsigned int index,
                int val )
{
  unsigned int length = ia->len;
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index<length){
    ia->data[index] = val;
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

// If index is valid and i is non-null, set *i to ia->data[index] and return
// INTARR_OK. Otherwise no not modify *i and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_get( const intarr_t* ia,
                unsigned int index,
                int* i )
{
  if(ia->data == NULL){
    return INTARR_BADARRAY;
  }
  if(index< ia->len){
    i = &(ia->data[index]);
    return INTARR_OK;
  }else{
    return INTARR_BADINDEX;
  }
}

/* LAB 5 TASK 3 */

// Return a duplicate of ia, allocating new storage for the duplicate
// data (we call this a "deep copy"). If unsuccessful (i.e. memory
// allocation for the copy fails, or ia is null), return a null pointer.
intarr_t* intarr_copy( const intarr_t* ia )
{
  intarr_t* newArr = intarr_create(ia->len);
}

/* LAB 5 TASK 4 */

// sort ia by value smallest-to-largest, so that data[i] < data[i+1]
// for all valid i, then return INTARR_OK. Works in-place: contents of
// ia are sorted on return. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_sort( intarr_t* ia )
{
}

/* LAB 5 TASK 5 */

// Find the first occurence of the target in the array, searching from
// index 0. If the target is found and i is non-null, set *i to the
// location index and return INTARR_OK. If target does not occur in
// the array, leave *i unmodified and return INTARR_NOTFOUND. If ia is
// null, return INTARR_BADARRAY.
intarr_result_t intarr_find( intarr_t* ia, int target, int* i )
{
}

/* LAB 5 TASK 6 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_push( intarr_t* ia, int val )
{
}

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
}

/* LAB 5 TASK 7 */

// Resize ia to contain newlen values. If newlen is less than the
// original array length, the end of the array is discarded. If newlen
// is greater than the original array length, intialize all the new
// integers to zero. If the allocation is successful, return
// INTARR_OK, otherwise return INTARR_BADALLOC. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_resize( intarr_t* ia, unsigned int newlen )
{
}

/* LAB 5 TASK 8 */

// Get a deep copy of a portion of ia from index first to index last
// inclusive. If successful, return a pointer to a newly-allocated
// intarr_t containing a copy of the specfied section. If an error
// occurs, i.e. ia is null, first or last are out of bounds, last <
// first, or memory allocation fails, return a null pointer.
intarr_t* intarr_copy_subarray( intarr_t* ia,
                unsigned int first,
                unsigned int last )
{
}

/* LAB 5 ENDS HERE */

/* -------------------------------------------------------------- */

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
}


/* LAB 6 TASK 2 */

/*
  Save the entire array ia into a file called 'filename' in a JSON
  text file array file format that can be loaded by
  intarr_load_json(). Returns zero on success, or a non-zero error
  code on failure. Arrays of length 0 should produce an output file
  containing an empty array.

  The JSON output should be human-readable.

  Examples:

  The following line is a valid JSON array:
  [ 100, 200, 300 ]

  The following lines are a valid JSON array:
  [
   100,
   200,
   300
  ]
*/
int intarr_save_json( intarr_t* ia, const char* filename )
{
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_json(). The file may contain an array
  of length 0. Returns a pointer to a newly-allocated intarr_t on
  success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename )
{
}

Sunday, June 25, 2017

t1

void draw_circle( uint8_t img[],
                  unsigned int cols,
                  unsigned int rows,
                  int x,
                  int y,
                  int r,
                  uint8_t color )
{
  int leftT, rightT, leftB, rightB;
  //vertical = radius
  if(x<cols && x>=0){
    for(int i=y-r; i<=y+r; i++){
      if(i>=0 && i<rows){
        img[x+i*cols]=color;
      }
    }
  }

  //horizontal = radius
  if(y>=0 && y<rows){
    for(int i=x-r; i<=x+r; i++){
      if(i>=0 && i<cols){
        img[i+y*cols]=color;
      }
    }
  }

  // y= y1 + (sqrt)(r^2-x^2)
  for(int xx =1; xx<=r; xx++){
    int yy= (int)(sqrt(r*r - xx*xx)+1);
    // top left to top right - indexes
    leftT = x-xx+(y-yy)*cols;
    rightT = x+xx+(y-yy)*cols;
    //for loop to draw one line across
    for(int i=leftT; i<=rightT; i++){
      if(i>=0 && i<cols*rows){
        img[i]=color;
      }
    }

    //bottom left to bottom right
    leftB = x-xx+(y+yy)*cols;
    rightB = x+xx+(y+yy)*cols;
    for(int i=leftB; i<=rightB; i++){
      if(i>=0 && i<cols*rows){
        img[i]=color;
      }
    }
  }
}

draw circle

void draw_circle( uint8_t img[],
                  unsigned int cols,
                  unsigned int rows,
                  int x,
                  int y,
                  int r,
                  uint8_t color )
{
  int leftT, rightT, leftB, rightB;
  //vertical = radius
  if(x<cols && x>=0){
    for(int i=y-r; i<=y+r; i++){
      if(i>=0 && i<rows){
        img[x+i*cols]=color;
      }
    }
  }

  //horizontal = radius
  if(y>=0 && y<rows){
    for(int i=x-r; i<=x+r; i++){
      if(i>=0 && i<cols){
        img[i+y*cols]=color;
      }
    }
  }

  // y= y1 + (sqrt)(r^2-x^2)
  for(int xx =1; xx<r; xx++){
    int yy= (int)sqrt(r**2 - xx**2)+y;
    // top left to top right - indexes
    leftT = x-xx+(y-yy)*cols;
    rightT = x+xx+(y-yy)*cols;
    //for loop to draw one line across
    for(int i=leftT; i<=rightT; i++){
      if(i>=0 && i<cols*rows){
        img[i]=color;
      }
    }

    //bottom left to bottom right
    leftB = x-xx+(y+yy)*cols;
    rightB = x+xx+(y+yy)*cols;
    for(int i=leftB; i<=rightB; i++){
      if(i>=0 && i<cols*rows){
        img[i]=color;
      }
    }
  }
}

Wednesday, June 21, 2017

intarr

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* LAB 5 TASK 1 */

// Create a new intarr_t with initial size len.  If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated intarr_t.  If unsuccessful, returns a null pointer.
intarr_t* intarr_create( unsigned int len )
{
    intarr_t*pointer = malloc(sizeof(unsigned int)*len);
    if (pointer == NULL){
        return NULL;
    }
    return pointer;
}

// frees all memory allocated for ia. If the pointer is null, do
// nothing. If the ia->data is null, do not attempt to free it.
void intarr_destroy( intarr_t* ia )
{
    if(ia != NULL){
        free(ia);
    }
}

/* LAB 5 TASK 2 */

// If index is valid, set the value at ia->data[index] to val and return
// INTARR_OK. Otherwise, leave the array unmodified and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_set( intarr_t* ia,
                unsigned int index,
                int val )
{
    /*if(ia != NULL){
        if
        ia[index] = val;
        return INTARR_OK;
    } else {
        return*/
}

// If index is valid and i is non-null, set *i to ia->data[index] and return
// INTARR_OK. Otherwise no not modify *i and return
// INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_get( const intarr_t* ia,
                unsigned int index,
                int* i )
{
}

/* LAB 5 TASK 3 */

// Return a duplicate of ia, allocating new storage for the duplicate
// data (we call this a "deep copy"). If unsuccessful (i.e. memory
// allocation for the copy fails, or ia is null), return a null pointer.
intarr_t* intarr_copy( const intarr_t* ia )
{
}

/* LAB 5 TASK 4 */

// sort ia by value smallest-to-largest, so that data[i] < data[i+1]
// for all valid i, then return INTARR_OK. Works in-place: contents of
// ia are sorted on return. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_sort( intarr_t* ia )
{
}

/* LAB 5 TASK 5 */

// Find the first occurence of the target in the array, searching from
// index 0. If the target is found and i is non-null, set *i to the
// location index and return INTARR_OK. If target does not occur in
// the array, leave *i unmodified and return INTARR_NOTFOUND. If ia is
// null, return INTARR_BADARRAY.
intarr_result_t intarr_find( intarr_t* ia, int target, int* i )
{
}

/* LAB 5 TASK 6 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_push( intarr_t* ia, int val )
{
}

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
// Take a look at TASK 7 below and see if it might be helpful
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
}

/* LAB 5 TASK 7 */

// Resize ia to contain newlen values. If newlen is less than the
// original array length, the end of the array is discarded. If newlen
// is greater than the original array length, intialize all the new
// integers to zero. If the allocation is successful, return
// INTARR_OK, otherwise return INTARR_BADALLOC. If ia is null, return
// INTARR_BADARRAY.
intarr_result_t intarr_resize( intarr_t* ia, unsigned int newlen )
{
}

/* LAB 5 TASK 8 */

// Get a deep copy of a portion of ia from index first to index last
// inclusive. If successful, return a pointer to a newly-allocated
// intarr_t containing a copy of the specfied section. If an error
// occurs, i.e. ia is null, first or last are out of bounds, last <
// first, or memory allocation fails, return a null pointer.
intarr_t* intarr_copy_subarray( intarr_t* ia,
                unsigned int first,
                unsigned int last )
{
}

/* LAB 5 ENDS HERE */

/* -------------------------------------------------------------- */

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
}


/* LAB 6 TASK 2 */

/*
  Save the entire array ia into a file called 'filename' in a JSON
  text file array file format that can be loaded by
  intarr_load_json(). Returns zero on success, or a non-zero error
  code on failure. Arrays of length 0 should produce an output file
  containing an empty array.
 
  The JSON output should be human-readable.

  Examples:

  The following line is a valid JSON array:
  [ 100, 200, 300 ]
 
  The following lines are a valid JSON array:
  [
   100,
   200,
   300
  ]
*/
int intarr_save_json( intarr_t* ia, const char* filename )
{
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_json(). The file may contain an array
  of length 0. Returns a pointer to a newly-allocated intarr_t on
  success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename )
{
}

imgops

void normalize( uint8_t array[],
        unsigned int cols,
        unsigned int rows )
{
uint8_t darkest = min(array, cols, rows);
uint8_t lightest = max(array, cols, rows);
  uint8_t arr[lightest-darkest+1];
double scale_factor = (255/(lightest-darkest));
  int k =0;
  for(int i=darkest; i<lightest-darkest+1; i++){
    arr[k] = i;
    k++;
  }
  for(int i=0; i<cols*rows; i++){
    for(int k=0; k<lightest-darkest+1; k++){
      if(array[i] == arr[k]){
        double new = round(k*scale_factor);
        array[i] = (uint8_t) new;
        break;
      }
    }
  }
}

Tuesday, June 20, 2017

imgops

/*
 * imageops.c - Simple operations on images
 *
 * C laboratory exercises.
 * Richard Vaughan, 2014.
 */

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/*-------------------------------------------------
  PART 0: DEMONSTRATION
*/


// get the value in the array at coordinate (x,y)
uint8_t get_pixel( const uint8_t array[],
           unsigned int cols,
           unsigned int rows,
           unsigned int x,
           unsigned int y )
{
    assert( x < cols );
    assert( y < rows );
    return array[ y*cols + x ];
}

// set the pixel at coordinate {x,y} to the specified color
void set_pixel( uint8_t array[],
        unsigned int cols,
        unsigned int rows,
        unsigned int x,
        unsigned int y,
        uint8_t color )
{
    assert( x < cols );
    assert( y < rows );
    array[ y * cols + x ] = color;
}

// Set every pixel to 0 (black)
void zero( uint8_t array[],
  unsigned int cols,
  unsigned int rows )
{
  // your code here.
}

// Returns a pointer to a freshly allocated array that contains the
// same values as the original array, or a null pointer if the
// allocation fails. The caller is responsible for freeing the array
// later.
uint8_t* copy( const uint8_t array[],
           unsigned int cols,
           unsigned int rows )
{
  // your code here
  /*uint8_t* cp = malloc(cols*rows*sizeof(uint8_t)); //creates new array
  if(cp ==NULL) return NULL;
  for(int i =0; i<rows; y++){
    for(int x =0; i<cols; x++){

    }
  }*/
  return NULL;
}



/*-------------------------------------------------
  PART 1: OPERATIONS ON THE WHOLE IMAGE
*/

/* TASK 1 - three easy functions to get started */

// Return the darkest color that appears in the array; i.e. the
// smallest value
uint8_t min( const uint8_t array[],
    unsigned int cols,
    unsigned int rows )
{
    int dark = array[0];
    for(int i=1; i<cols*rows; i++){
        if(array[i]<dark){
            dark = array[i];
        }
    }
    return dark;
}

// Return the lightest color that appears in the array; i.e. the
// largest value
uint8_t max( const uint8_t array[],
unsigned int cols,
unsigned int rows )
{
    int light = array[0];
    for(int i =1; i<cols*rows; i++){
        if(array[i]> light){
            light = array[i];
        }
    }
    return light;
}

// TASK 2

//  Replace every instance of pre_color with post_color.
void replace_color(  uint8_t array[],
    unsigned int cols,
    unsigned int rows,
    uint8_t pre_color,
    uint8_t post_color )
{
    for(int i=0; i<cols*rows; i++){
        if(array[i] == pre_color){
            array[i] = post_color;
        }
    }
}

/* TASK 3  - two functions */


// flip the image, left-to-right, like in a mirror.
void flip_horizontal( uint8_t array[],
              unsigned int cols,
              unsigned int rows )
{
    int start, end, temp;
    for(int i=0; i<rows; i++){
        start = i*cols;
        end = (cols-1)+i*cols;
        while(start<end){
            temp= array[start];
            array[start] = array[end];
            array[end] = temp;
            start++;
            end--;
        }
    }
}

// flip the image top-to-bottom.
void flip_vertical( uint8_t array[],
            unsigned int cols,
            unsigned int rows )
{
    int start1, start2, temp;
    int startrow = 0, endrow= rows-1;
    while(startrow<endrow){
        start1=startrow*cols;
        start2=endrow*cols;
        for(int i =0; i<cols; i++){
            temp = array[start1];
            array[start1] = array[start2];
            array[start2] = temp;
            start1++;
            start2++;
        }
        startrow++;
        endrow--;
    }
}

/* TASK 4 */

// Find the first coordinate of the first pixel with a value that
// equals color. Search from left-to-right, top-to-bottom. If it is
// found, store the coordinates in *x and *y and return 1. If it is
// not found, return 0.
int locate_color(  const uint8_t array[],
  unsigned int cols,
  unsigned int rows,
  uint8_t color,
  unsigned int *x,
  unsigned int *y )
{
    int found =0, index;
    for(unsigned int yy =0; yy<rows; yy++){
        for(unsigned int xx=0; xx<cols;xx++){
            index = xx + yy*cols;
            if( array[index] == color ){
                *x = xx;
                *y = yy;
                found = 1;
                break;
            }
        }
        if( found == 1 ){
            break;
        }
    }
    return found;
}


/* TASK 5 */

// Invert the image, so that black becomes white and vice versa, and
// light shades of grey become the corresponding dark shade.
void invert( uint8_t array[],
         unsigned int cols,
         unsigned int rows )
{
    uint8_t greyscale[256];
    int color = 255;
    // create an array with numbers 0 to 255:
    for(int i =0; i< 256; i++){
        greyscale[i] = color;
        color--;
    }
    // inverts the image:
    for(int k=0; k<cols*rows; k++){
        array[k] = greyscale[array[k]];
    }
}

/* TASK 6 */

// Multiply every pixel by scale_factor, in order to brighten or
// darken the image. Any resulting value over 255 is
// thresholded to 255.
void scale_brightness( uint8_t array[],
            unsigned int cols,
            unsigned int rows,
            double scale_factor )
{
for(int i=0; i<cols*rows; i++){
double k= round((double) array[i] * scale_factor);
if(k <= 255){
array[i] = (uint8_t) k;
    }else{
      array[i] = 255;
    }
}
}


/* TASK 7 */

// Normalize the dynamic range of the image, i.e. Shift and scale the
// pixel colors so that that darkest pixel is 0 and the lightest pixel
// is 255. Hint: you already wrote min() and max().
void normalize( uint8_t array[],
        unsigned int cols,
        unsigned int rows )
{
uint8_t darkest = min(array, cols, rows);
uint8_t lightest = max(array, cols, rows);
  uint8_t arr[lightest-darkest+1];
double scale_factor = (round) (256/(max-min+1));
  for(int i=darkest; i<lightest-darkest+1; i++){
    arr[i] = i;
  }
  for(int i=0; i<cols*rows; i++){
    for(uint8_t k=0; k<lightest-darkest+1; i++){
      if(arr[k] == array[i]){
        double new = k*scale_factor;
        array[i] = (uint8_t) new;
        break;
      }
    }
  }
}

/* TASK 8 */

// Return a new image of size rows/2 by cols/2 If the original image
// has an odd number of columns, ignore its rightmost column. If the
// original image has an odd number of rows, ignore its bottom row.
// The value of a pixel at (p,q) in the new image is the average of
// the four pixels at (2p,2q), (2p+1,2q), (2p+1,2q+1), (2p,2q+1) in
// the original image.
uint8_t* half( const uint8_t array[],
      unsigned int cols,
      unsigned int rows )
{
  // creates a new array
  unsigned int newCols, newRows;
if(cols %2 != 0 ){
newCols = cols-1;
} else if(rows%2 != 0){
newRows = rows-1;
}
newCols = newCols/2;
newRows = newRows/2;
  uint8_t* arr= malloc(newCols*newRows*sizeof(uint8_t));

  //  changes values of each element
  for(int y=0; y<newRows; y++){
    for(int x =0; x<newCols; x++){
        // creates an average of four pixels
        uint8_t p22q = array[2*x+2*y*cols];
        uint8_t p21_2q = array[(2*x+1)+2*y*cols];
        uint8_t p21_2q1 = array[(2*x+1)+(2*y+1)*cols];
        uint8_t p2_2q1 = array[(2*x)+(2*y+1)*cols];

        double avg = round((p22q+p21_2q1+p21_2q+p2_2q1)/4);
        arr[x+y*cols]= (uint8_t)avg;
    }

  }
return arr;
}




/*-------------------------------------------------
  PART 2: OPERATIONS ON IMAGE SUB-REGIONS

  These functions operate only on a rectangular region of the array
  defined by a (left,top) corner (i.e. closer to the image origin) and
  (right,bottom) corner (i.e. further from the image origin).

  The region includes all the columns from [left, right-1] inclusive,
  and allthe rows from [top, bottom-1] inclusive.

  In every case, you may assume that left <= right and top <= bottom:
  do not need to test for this.

  The area of the region is right-left * bottom-top pixels, which
  implies that if left == right or top == bottom, the region has no
  area and is defined as "empty". Each function notes how to handle
  empty regions.

  In every function, use assert() to test bounds on the region
  corners.
*/

/* TASK 9 */

// Set every pixel in the region to color. If the region is empty, the
// image must be unchanged.
void region_set( uint8_t array[],
         unsigned int cols,
         unsigned int rows,
         unsigned int left,
         unsigned int top,
         unsigned int right,
         unsigned int bottom,
         uint8_t color )
{
for(int y=0; y<rows; y++){
if( y == bottom ){
break;
}
if( (y >= top) && (y < bottom)){
for(int x=0; x<cols; x++){
if( (x >= left) && (x < right)){
array[(x+y*cols)] = color;
}
}
}
}
}

/* TASK 10 */

// Return the sum of all the pixels in the region. Notice the large
// return type to handle potentially large numbers. Empty regions
// return the sum 0.
unsigned long int region_integrate( const uint8_t array[],
                    unsigned int cols,
                    unsigned int rows,
                    unsigned int left,
                    unsigned int top,
                    unsigned int right,
                    unsigned int bottom )
{
unsigned long int sum = 0;
for( int y=0; y<rows; y++){
if(y == bottom){
break;
}
if( (y>= top) && (y<bottom) ){
for(int x=0; x<cols; x++){
        if( (x >= left) && (x< right)){
     sum = sum + array[(x+y*cols)];
        }
}
}
}
return sum;
}

/* TASK 11 */

// Get a new image which is a copy of the region. Empty regions return
// a null pointer. If memory allocation fails, return a null
// pointer. The caller is responsible for freeing the returned array
// later.
uint8_t* region_copy( const uint8_t array[],
              unsigned int cols,
              unsigned int rows,
              unsigned int left,
              unsigned int top,
              unsigned int right,
              unsigned int bottom )
{
  uint8_t*arr = malloc(cols*rows*sizeof(uint8_t));
  int i =0;
  if (arr == 0){
    return NULL;
  }
  if ((left == right) || (top == bottom)){
    return NULL;
  }
  for( int y=0; y<rows; y++){
    if(y == bottom){
      break;
    }
    if( (y>= top) && (y<bottom) ){
      for(int x=0; x<cols; x++){
        if( (x >= left) && (x< right)){
              arr[i] = array[x+y*cols];
              i++;
        }
      }
    }
  }
  return arr;
}

Sunday, June 18, 2017

imgops

/*
 * imageops.c - Simple operations on images
 *
 * C laboratory exercises.
 * Richard Vaughan, 2014.
 */

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/*-------------------------------------------------
  PART 0: DEMONSTRATION
*/


// get the value in the array at coordinate (x,y)
uint8_t get_pixel( const uint8_t array[],
           unsigned int cols,
           unsigned int rows,
           unsigned int x,
           unsigned int y )
{
    assert( x < cols );
    assert( y < rows );
    return array[ y*cols + x ];
}

// set the pixel at coordinate {x,y} to the specified color
void set_pixel( uint8_t array[],
        unsigned int cols,
        unsigned int rows,
        unsigned int x,
        unsigned int y,
        uint8_t color )
{
    assert( x < cols );
    assert( y < rows );
    array[ y * cols + x ] = color;
}

// Set every pixel to 0 (black)
void zero( uint8_t array[],
  unsigned int cols,
  unsigned int rows )
{
  // your code here.
}

// Returns a pointer to a freshly allocated array that contains the
// same values as the original array, or a null pointer if the
// allocation fails. The caller is responsible for freeing the array
// later.
uint8_t* copy( const uint8_t array[],
           unsigned int cols,
           unsigned int rows )
{
  // your code here
  /*uint8_t* cp = malloc(cols*rows*sizeof(uint8_t)); //creates new array
  if(cp ==NULL) return NULL;
  for(int i =0; i<rows; y++){
    for(int x =0; i<cols; x++){

    }
  }*/
  return NULL;
}



/*-------------------------------------------------
  PART 1: OPERATIONS ON THE WHOLE IMAGE
*/

/* TASK 1 - three easy functions to get started */

// Return the darkest color that appears in the array; i.e. the
// smallest value
uint8_t min( const uint8_t array[],
    unsigned int cols,
    unsigned int rows )
{
    int dark = array[0];
    for(int i=1; i<cols*rows; i++){
        if(array[i]<dark){
            dark = array[i];
        }
    }
    return dark;
}

// Return the lightest color that appears in the array; i.e. the
// largest value
uint8_t max( const uint8_t array[],
unsigned int cols,
unsigned int rows )
{
    int light = array[0];
    for(int i =1; i<cols*rows; i++){
        if(array[i]> light){
            light = array[i];
        }
    }
    return light;
}

// TASK 2

//  Replace every instance of pre_color with post_color.
void replace_color(  uint8_t array[],
    unsigned int cols,
    unsigned int rows,
    uint8_t pre_color,
    uint8_t post_color )
{
    for(int i=0; i<cols*rows; i++){
        if(array[i] == pre_color){
            array[i] = post_color;
        }
    }
}

/* TASK 3  - two functions */


// flip the image, left-to-right, like in a mirror.
void flip_horizontal( uint8_t array[],
              unsigned int cols,
              unsigned int rows )
{
    int start, end, temp;
    for(int i=0; i<rows; i++){
        start = i*cols;
        end = (cols-1)+i*cols;
        while(start<end){
            temp= array[start];
            array[start] = array[end];
            array[end] = temp;
            start++;
            end--;
        }
    }
}

// flip the image top-to-bottom.
void flip_vertical( uint8_t array[],
            unsigned int cols,
            unsigned int rows )
{
    int start1, start2, temp;
    int startrow = 0, endrow= rows-1;
    while(startrow<endrow){
        start1=startrow*cols;
        start2=endrow*cols;
        for(int i =0; i<cols; i++){
            temp = array[start1];
            array[start1] = array[start2];
            array[start2] = temp;
            start1++;
            start2++;
        }
        startrow++;
        endrow--;
    }
}

/* TASK 4 */

// Find the first coordinate of the first pixel with a value that
// equals color. Search from left-to-right, top-to-bottom. If it is
// found, store the coordinates in *x and *y and return 1. If it is
// not found, return 0.
int locate_color(  const uint8_t array[],
  unsigned int cols,
  unsigned int rows,
  uint8_t color,
  unsigned int *x,
  unsigned int *y )
{
    int found =0, index;
    for(unsigned int yy =0; yy<rows; yy++){
        for(unsigned int xx=0; xx<cols;xx++){
            index = xx + yy*cols;
            if( array[index] == color ){
                *x = xx;
                *y = yy;
                found = 1;
                break;
            }
        }
        if( found == 1 ){
            break;
        }
    }
    return found;
}


/* TASK 5 */

// Invert the image, so that black becomes white and vice versa, and
// light shades of grey become the corresponding dark shade.
void invert( uint8_t array[],
         unsigned int cols,
         unsigned int rows )
{
    uint8_t greyscale[256];
    int color = 255;
    // create an array with numbers 0 to 255:
    for(int i =0; i< 256; i++){
        greyscale[i] = color;
        color--;
    }
    // inverts the image:
    for(int k=0; k<cols*rows; k++){
        array[k] = greyscale[array[k]];
    }
}

/* TASK 6 */

// Multiply every pixel by scale_factor, in order to brighten or
// darken the image. Any resulting value over 255 is
// thresholded to 255.
void scale_brightness( uint8_t array[],
            unsigned int cols,
            unsigned int rows,
            double scale_factor )
{
for(int i=0; i<cols*rows; i++){
double k= round((double) array[i] * scale_factor);
if(k <= 255){
array[i] = (uint8_t) k;
    }else{
      array[i] = 255;
    }
}
}


/* TASK 7 */

// Normalize the dynamic range of the image, i.e. Shift and scale the
// pixel colors so that that darkest pixel is 0 and the lightest pixel
// is 255. Hint: you already wrote min() and max().
void normalize( uint8_t array[],
        unsigned int cols,
        unsigned int rows )
{
uint8_t darkest = min(array, cols, rows);
uint8_t lightest = max(array, cols, rows);
  uint8_t arr[lightest-darkest+1];
double scale_factor = (round) (256/(max-min+1));
  for(int i=darkest; i<lightest-darkest+1; i++){
    arr[i] = i;
  }
  for(int i=0; i<cols*rows; i++){
    for(uint8_t k=0; k<lightest-darkest+1; i++){
      if(arr[k] == array[i]){
        double new = k*scale_factor;
        array[i] = (uint8_t) new;
        break;
      }
    }
  }
}

/* TASK 8 */

// Return a new image of size rows/2 by cols/2 If the original image
// has an odd number of columns, ignore its rightmost column. If the
// original image has an odd number of rows, ignore its bottom row.
// The value of a pixel at (p,q) in the new image is the average of
// the four pixels at (2p,2q), (2p+1,2q), (2p+1,2q+1), (2p,2q+1) in
// the original image.
uint8_t* half( const uint8_t array[],
      unsigned int cols,
      unsigned int rows )
{
  // creates a new array
  unsigned int newCols, newRows;
if(cols %2 != 0 ){
newCols = cols-1;
} else if(rows%2 != 0){
newRows = rows-1;
}
newCols = newCols/2;
newRows = newRows/2;
  uint8_t arr[newCols*newRows];

  //  changes values of each element
  for(int y=0; y<rows; y++){
    for(int x =0; x<cols; x++){
        // creates an average of four pixels
        uint8_t 2p2q = array[2*x+2*y*cols];
        uint8_t 2p1_2q = array[(2*x+1)+2*y*cols];
        uint8_t 2p1_2q1 = array[(2*x+1)+(2*y+1)*cols];
        uint8_t 2p_2q1 = array[(2*x)+(2*y+1)*cols];

        double avg = (2p2q+2p1_2q1+2p1_2q+2p_2q1)/4;
        arr[x+y*cols]= (uint8_t)avg;
    }

  }
return arr;
}




/*-------------------------------------------------
  PART 2: OPERATIONS ON IMAGE SUB-REGIONS

  These functions operate only on a rectangular region of the array
  defined by a (left,top) corner (i.e. closer to the image origin) and
  (right,bottom) corner (i.e. further from the image origin).

  The region includes all the columns from [left, right-1] inclusive,
  and allthe rows from [top, bottom-1] inclusive.

  In every case, you may assume that left <= right and top <= bottom:
  do not need to test for this.

  The area of the region is right-left * bottom-top pixels, which
  implies that if left == right or top == bottom, the region has no
  area and is defined as "empty". Each function notes how to handle
  empty regions.

  In every function, use assert() to test bounds on the region
  corners.
*/

/* TASK 9 */

// Set every pixel in the region to color. If the region is empty, the
// image must be unchanged.
void region_set( uint8_t array[],
         unsigned int cols,
         unsigned int rows,
         unsigned int left,
         unsigned int top,
         unsigned int right,
         unsigned int bottom,
         uint8_t color )
{
for(int y=0; y<rows; y++){
if( y == bottom ){
break;
}
if( (y >= top) && (y < bottom)){
for(int x=0; x<cols; x++){
if( (x >= left) && (x < right)){
array[(x+y*cols)] = color;
}
}
}
}
}

/* TASK 10 */

// Return the sum of all the pixels in the region. Notice the large
// return type to handle potentially large numbers. Empty regions
// return the sum 0.
unsigned long int region_integrate( const uint8_t array[],
                    unsigned int cols,
                    unsigned int rows,
                    unsigned int left,
                    unsigned int top,
                    unsigned int right,
                    unsigned int bottom )
{
unsigned long int sum = 0;
for( int y=0; y<rows; y++){
if(y == bottom){
break;
}
if( (y>= top) && (y<bottom) ){
for(int x=0; x<cols; x++){
        if( (x >= left) && (x< right)){
     sum = sum + array[(x+y*cols)];
        }
}
}
}
return sum;
}

/* TASK 11 */

// Get a new image which is a copy of the region. Empty regions return
// a null pointer. If memory allocation fails, return a null
// pointer. The caller is responsible for freeing the returned array
// later.
uint8_t* region_copy( const uint8_t array[],
              unsigned int cols,
              unsigned int rows,
              unsigned int left,
              unsigned int top,
              unsigned int right,
              unsigned int bottom )
{
  uint8_t*arr = malloc(cols*rows*sizeof(uint8_t));
  // your code here
  free(arr);
  return NULL;
}