Esempio n. 1
0
int main() 
{
    int length = 25;
    int a[length];

    srand((int)time(0));
    for (int i = 0; i < length; i++)
        a[i] = random(100); 

    for (int i = 0; i < length; i++)
        std::cout << a[i] << " ";
    std::cout << std::endl;

    std::pair<int, int> res = find_min_max(a, length);
    std::cout << "min: " << res.first << " max: " << res.second << std::endl;
}
Esempio n. 2
0
      void Orderizer::load_data(const char* filename)
      {
        FILE* f = fopen(filename, "rb");
        if (f == NULL) error("Could not open %s for reading.", filename);
        lock_data();

        struct { char magic[4]; int ver; } hdr;
        if (fread(&hdr, sizeof(hdr), 1, f) != 1)
          error("Error reading %s", filename);

        if (hdr.magic[0] != 'H' || hdr.magic[1] != '2' || hdr.magic[2] != 'D' || hdr.magic[3] != 'O')
          error("File %s is not a Hermes2D Orderizer<Scalar> file.", filename);
        if (hdr.ver > 1)
          error("File %s -- unsupported file version.", filename);

#define read_array(array, type, n, c, what) \
  if (fread(&n, sizeof(int), 1, f) != 1) \
  error("Error reading the number of " what " from %s", filename); \
  lin_init_array(array, type, c, n); \
  if (fread(array, sizeof(type), n, f) != (unsigned) n) \
  error("Error reading " what " from %s", filename);

        read_array(verts, double3, nv, cv,  "vertices");
        read_array(tris,  int3,    nt, ct,  "triangles");
        read_array(edges, int3,    ne, ce,  "edges");
        read_array(lvert, int,     nl, cl1, "label vertices");

        lin_init_array(lbox, double2, cl3, nl);
        if (fread(lbox, sizeof(double2), nl, f) != (unsigned) nl)
          error("Error reading label bounding boxes from %s", filename);

        int* orders = new int[nl];
        if (fread(orders, sizeof(int), nl, f) != (unsigned) nl)
          error("Error reading element orders from %s", filename);

        lin_init_array(ltext, char*, cl2, nl);
        for (int i = 0; i < nl; i++)
          ltext[i] = labels[H2D_GET_H_ORDER(orders[i])][H2D_GET_V_ORDER(orders[i])];

        find_min_max();
        unlock_data();
        fclose(f);
      }
Esempio n. 3
0
double *makeSequence(long *points, double start, double end, double spacing, double *data, long dataRows)
{
  long i;
  double delta, *sequence;
  if (start==end) {
    if (!find_min_max(&start, &end, data, dataRows))
      return NULL;
  }
  if (*points>1) {
    delta = (end-start)/(*points-1);
  } else if (spacing>=0) {
    delta = spacing;
    *points = (end-start)/delta + 1.5;
  } else{
    *points = 1;
    delta = 0;
  }
  sequence = tmalloc(sizeof(*sequence)*(*points));
  for (i=0; i<*points; i++)
    sequence[i] = start+delta*i;
  return sequence;
}
Esempio n. 4
0
long find_middle(double *value, double *data, long n)
{
    double target, min_dist, dist, min, max;
    long i, i_best;

    if (n<=0)
        return(-1);

    if (!find_min_max(&min, &max, data, n))
        return(-1);
    target = (min+max)/2;

    min_dist = DBL_MAX;
    i_best = -1;
    for (i=0; i<n; i++)
        if ((dist=fabs(data[i]-target))<min_dist) {
            min_dist = dist;
            i_best = i;
            }    
    *value = target;
    return(i_best);
    }
Esempio n. 5
0
void computeChromaticTuneLimits(LINE_LIST *beamline)
{
  long i, j, n, p;
  double c1, c2, c3, tuneValue[5], solution[2];
  
  for (i=0; i<2; i++) {
    if (beamline->chromDeltaHalfRange<=0) {
      beamline->tuneChromUpper[i] = beamline->tuneChromLower[i] = beamline->tune[i];
    } else {
      tuneValue[0] = beamline->tune[i];
      /* polynomial coefficients */
      c1 = beamline->chromaticity[i];
      c2 = beamline->chrom2[i]/2.0;
      c3 = beamline->chrom3[i]/6.0;
      tuneValue[1] = beamline->tune[i] + 
        beamline->chromDeltaHalfRange*c1 + 
          sqr(beamline->chromDeltaHalfRange)*c2 +
            ipow(beamline->chromDeltaHalfRange, 3)*c3;
      tuneValue[2] = beamline->tune[i] -
        beamline->chromDeltaHalfRange*c1 + 
          sqr(beamline->chromDeltaHalfRange)*c2 -
            ipow(beamline->chromDeltaHalfRange, 3)*c3;
      p = 3;
      /* find extrema */
      n = solveQuadratic(3*c3, 2*c2, c1, solution);
      for (j=0; j<n; j++) {
        if (fabs(solution[j])>beamline->chromDeltaHalfRange)
          continue;
        tuneValue[p] = beamline->tune[i] +
          solution[j]*c1 + sqr(solution[j])*c2 +
            ipow(solution[j], 3)*c3;
        p += 1;
      }
      find_min_max(beamline->tuneChromLower+i, beamline->tuneChromUpper+i, 
                   tuneValue, p);
    }
  }
}
Esempio n. 6
0
/*
 * The splitting routine is essentially a median search,
 * i.e. finding the median and split the array about it.
 * There are several algorithms for the median search
 * (an overview is given at http://ndevilla.free.fr/median/median/index.html):
 * - AHU (1)
 * - WIRTH (2)
 * - QUICKSELECT (3)
 * - TORBEN (4)
 * (1) and (2) are essentially the same in recursive and non recursive versions.
 * (2) is among the fastest in sequential programs.
 * (3) is similar to what quicksort uses and is as fast as (2).
 * Both (2) and (3) require permuting array elements.
 * (4) is significantly slower but only reads the array without modifying it.
 * The implementation below is a simplified version of (2).
 
*/
void split_bounding_box(data_type_short *points, uint *idx, uint n, data_type_short *bnd_lo, data_type_short *bnd_hi, uint *n_lo, uint *cdim, coord_type *cval)
{
    // search for dimension with longest egde
    coord_type longest_egde = bnd_hi->value[0] - bnd_lo->value[0];    
    uint dim = 0;
    
    for (uint d=0; d<D; d++) {        
        coord_type tmp = bnd_hi->value[d] - bnd_lo->value[d];
        if (longest_egde < tmp) {
            longest_egde = tmp;
            dim = d;
        }            
    }

    *cdim = dim;
    
    coord_type ideal_threshold = (bnd_hi->value[dim] + bnd_lo->value[dim]) / 2;    
    coord_type min,max;
    
    find_min_max(points,(idx+0),dim,n,&min,&max);
    
    coord_type threshold = ideal_threshold;
    
    if (ideal_threshold < min) {
        threshold = min;
    } else if (ideal_threshold > max) {
        threshold = max;
    }
    
    *cval = threshold;
    
    // Wirth's method
    int l = 0;
    int r = n-1;
       
    for(;;) {               // partition points[0..n-1]
    while (l < n && get_coord(points,idx+0,l,dim) < threshold) {
            l++;
        }
    while (r >= 0 && get_coord(points,idx+0,r,dim) >= threshold) {
            r--;
        }
    if (l > r) break; // avoid this
    coord_swap(idx+0,l,r);
    l++; r--;
    }
    
    uint br1 = l;           // now: data_points[0..br1-1] < threshold <= data_points[br1..n-1]
    r = n-1;
    for(;;) {               // partition pa[br1..n-1] about threshold
    while (l < n && get_coord(points,idx+0,l,dim) <= threshold) {
            l++;
        }
    while (r >= br1 && get_coord(points,idx+0,r,dim) > threshold) {
            r--;
        }
    if (l > r) break; // avoid this
    coord_swap(idx+0,l,r);
    l++; r--;
    }
    uint br2 = l;           // now: points[br1..br2-1] == threshold < points[br2..n-1]
    if (ideal_threshold < min) *n_lo = 0+1;
    else if (ideal_threshold > max) *n_lo = n-1;
    else if (br1 > n/2) *n_lo = br1;
    else if (br2 < n/2) *n_lo = br2;
    else *n_lo = n/2;
}
Esempio n. 7
0
void track_through_ztransverse(double **part, long np, ZTRANSVERSE *ztransverse, double Po,
                               RUN *run, long i_pass, CHARGE *charge
                               )
{
  static double *posItime[2] = {NULL, NULL};     /* array for particle density times x, y*/
  static double *posIfreq;                       /* array for FFT of particle density times x or y*/
  static double *Vtime = NULL;           /* array for voltage acting on each bin */
  static long max_n_bins = 0;
  static long *pbin = NULL;              /* array to record which bin each particle is in */
  static double *time = NULL;            /* array to record arrival time of each particle */
  static double *pz = NULL;
  static long max_np = 0;
  double *Vfreq, *iZ;
#if USE_MPI
  long i;
#endif
  long ib, nb, n_binned, nfreq, iReal, iImag, plane, first;
  double factor, tmin, tmax, tmean, dt, userFactor[2], rampFactor=1;
  static long not_first_call = -1;
  long ip, ip1, ip2, bunches, bunch, npb, i_pass0;
  long bucketEnd[MAX_BUCKETS];
#if USE_MPI
  float *buffer_send, *buffer_recv;
#endif
#if defined(DEBUG)
  FILE *fp;
#endif
  i_pass0 = i_pass;
  if ((i_pass -= ztransverse->startOnPass)<0)
    return;
  
  if (i_pass>=(ztransverse->rampPasses-1))
    rampFactor = 1;
  else
    rampFactor = (i_pass+1.0)/ztransverse->rampPasses;
  
  not_first_call += 1;

#if (!USE_MPI)
  if (np>max_np) {
    pbin = trealloc(pbin, sizeof(*pbin)*(max_np=np));
    time = trealloc(time, sizeof(*time)*max_np);
    pz = trealloc(pz, sizeof(*pz)*max_np);
  }
#else
    if (USE_MPI) {
      long np_total;
      if (isSlave) {
	MPI_Allreduce(&np, &np_total, 1, MPI_LONG, MPI_SUM, workers);
	if (np_total>max_np) { 
	  /* if the total number of particles is increased, we do reallocation for every CPU */
	  pbin = trealloc(pbin, sizeof(*pbin)*(max_np=np));
	  time = trealloc(time, sizeof(*time)*max_np);
	  pz = trealloc(pz, sizeof(*pz)*max_np);
	  max_np = np_total; /* max_np should be the sum across all the processors */
	}
      }
    } 
#endif
  
  if ((part[0][6]-floor(part[0][6]))!=0) {
    /* This is a kludgey way to determine that particles have been assigned to buckets */
    printf("Bunched beam detected\n"); fflush(stdout);
#if USE_MPI
    if (n_processors!=1) {
      printf("Error (ZTRANSVERSE): must have bunch_frequency=0 for parallel mode.\n");
      MPI_Barrier(MPI_COMM_WORLD); /* Make sure the information can be printed before aborting */
      MPI_Abort(MPI_COMM_WORLD, 2);
    }
#endif
    /* Start by sorting in bucket order */
    qsort(part[0], np, COORDINATES_PER_PARTICLE*sizeof(double), comp_BucketNumbers);
    /* Find the end of the buckets in the particle list */
    bunches = 0;
    for (ip=1; ip<np; ip++) {
      if ((part[ip-1][6]-floor(part[ip-1][6]))!=(part[ip][6]-floor(part[ip][6]))) {
        /* printf("Bucket %ld ends with ip=%ld\n", bunches, ip-1); fflush(stdout); */
        bucketEnd[bunches++] = ip-1;
        if (bunches>=MAX_BUCKETS) {
            bombElegant("Error (wake): maximum number of buckets was exceeded", NULL);
          }
      }
    }
    bucketEnd[bunches++] = np-1;
  } else {
    bunches = 1;
    bucketEnd[0] = np-1;
  }
  /* printf("Bucket %ld ends with ip=%ld\n", bunches, bucketEnd[bunches-1]); fflush(stdout); */

  ip2 = -1;
  for (bunch=0; bunch<bunches; bunch++) {
    ip1 = ip2+1;
    ip2 = bucketEnd[bunch];
    npb = ip2-ip1+1;
    /* printf("Processing bunch %ld with %ld particles\n", bunch, npb); fflush(stdout); */
    /* Compute time coordinate of each particle */
    tmean = computeTimeCoordinates(time+ip1, Po, part+ip1, npb);
    find_min_max(&tmin, &tmax, time+ip1, npb);
#if USE_MPI
    find_global_min_max(&tmin, &tmax, np, workers);      
#endif
    if (bunch==0) {
      /* use np here since we need to compute the macroparticle charge */
      set_up_ztransverse(ztransverse, run, i_pass, np, charge, tmax-tmin);
    }
    nb = ztransverse->n_bins;
    dt = ztransverse->bin_size;
    tmin -= dt;
    tmax -= dt;
    if ((tmax-tmin)*2>nb*dt) {
      TRACKING_CONTEXT tcontext;
      getTrackingContext(&tcontext);
      fprintf(stderr, "%s %s: Time span of bunch (%le s) is more than half the total time span (%le s).\n",
              entity_name[tcontext.elementType],
              tcontext.elementName,
              tmax-tmin, nb*dt);
      fprintf(stderr, "If using broad-band impedance, you should increase the number of bins and rerun.\n");
      fprintf(stderr, "If using file-based impedance, you should increase the number of data points or decrease the frequency resolution.\n");
      exitElegant(1);
    }

    if (nb>max_n_bins) {
      posItime[0] = trealloc(posItime[0], 2*sizeof(**posItime)*(max_n_bins=nb));
      posItime[1] = trealloc(posItime[1], 2*sizeof(**posItime)*(max_n_bins=nb));
      posIfreq = trealloc(posIfreq, 2*sizeof(*posIfreq)*(max_n_bins=nb));
      Vtime = trealloc(Vtime, 2*sizeof(*Vtime)*(max_n_bins+1));
    }

    for (ib=0; ib<nb; ib++)
      posItime[0][2*ib] = posItime[0][2*ib+1] = 
        posItime[1][2*ib] = posItime[1][2*ib+1] = 0;

    /* make arrays of I(t)*x and I(t)*y */
    n_binned = binTransverseTimeDistribution(posItime, pz, pbin, tmin, dt, nb, 
                                             time+ip1, part+ip1, Po, npb,
                                             ztransverse->dx, ztransverse->dy,
                                             ztransverse->xDriveExponent, ztransverse->yDriveExponent);
#if (!USE_MPI)
    if (n_binned!=npb) {
      fprintf(stdout, "Warning: only %ld of %ld particles were binned (ZTRANSVERSE)!\n", n_binned, npb);
      if (!not_first_call) {
        fprintf(stdout, "*** This may produce unphysical results.  Your wake needs smaller frequency\n");
        fprintf(stdout, "    spacing to cover a longer time span.\n");
      }
      fflush(stdout);
    }  
#else
    if (USE_MPI) {
      int all_binned, result = 1;
      if (isSlave)
        result = ((n_binned==np) ? 1 : 0);
      
      MPI_Allreduce(&result, &all_binned, 1, MPI_INT, MPI_LAND, workers);
      if (!all_binned) {
	if (myid==1) {  
	  /* This warning will be given only if the flag MPI_DEBUG is defined for the Pelegant */ 
	  fprintf(stdout, "warning: Not all of %ld particles were binned (WAKE)\n", np);
	  fprintf(stdout, "consider setting n_bins=0 in WAKE definition to invoke autoscaling\n");
	  fflush(stdout); 
	}
      }
    }
#endif

    userFactor[0] = ztransverse->factor*ztransverse->xfactor*rampFactor;
    userFactor[1] = ztransverse->factor*ztransverse->yfactor*rampFactor;

    first = 1;
    for (plane=0; plane<2; plane++) {
#if USE_MPI
      /* This could be good for some advanced network structures */
      /*
        if (isSlave) {
        double buffer[nb];
        MPI_Allreduce(posItime[plane], buffer, nb, MPI_DOUBLE, MPI_SUM, workers);
        memcpy(posItime[plane], buffer, sizeof(double)*nb);
        }
        */
      if (isSlave) {
        buffer_send = malloc(sizeof(float) * nb);
        buffer_recv = malloc(sizeof(float) * nb);
        for (i=0; i<nb; i++)
          buffer_send[i] = posItime[plane][i];
        MPI_Reduce(buffer_send, buffer_recv, nb, MPI_FLOAT, MPI_SUM, 1, workers);
        MPI_Bcast(buffer_recv, nb, MPI_FLOAT, 1, workers);
        for (i=0; i<nb; i++)
          posItime[plane][i] = buffer_recv[i];
        free(buffer_send);
        free(buffer_recv);
      }

#endif
      if (userFactor[plane]==0) {
        for (ib=0; ib<nb; ib++)
          Vtime[ib] = 0;
      } else {
        if (ztransverse->smoothing)
          SavitzyGolaySmooth(posItime[plane], nb, ztransverse->SGOrder,
                             ztransverse->SGHalfWidth, ztransverse->SGHalfWidth, 0);
        
        /* Take the FFT of (x*I)(t) to get (x*I)(f) */
        memcpy(posIfreq, posItime[plane], 2*nb*sizeof(*posIfreq));
        realFFT(posIfreq, nb, 0);
        
        /* Compute V(f) = i*Z(f)*(x*I)(f), putting in a factor 
         * to normalize the current waveform
         */
        Vfreq = Vtime;
        factor = ztransverse->macroParticleCharge*particleRelSign/dt*userFactor[plane];
        iZ = ztransverse->iZ[plane];
        Vfreq[0] = posIfreq[0]*iZ[0]*factor;
        nfreq = nb/2 + 1;
        if (nb%2==0)
          /* Nyquist term */
          Vfreq[nb-1] = posIfreq[nb-1]*iZ[nb-1]*factor;
        for (ib=1; ib<nfreq-1; ib++) {
          iImag = (iReal = 2*ib-1)+1;
          /* The signs are chosen here to get agreement with TRFMODE.
             In particular, test particles following closely behind the 
             drive particle get defocused.
             */
          Vfreq[iReal] =  (posIfreq[iReal]*iZ[iImag] + posIfreq[iImag]*iZ[iReal])*factor; 
          Vfreq[iImag] = -(posIfreq[iReal]*iZ[iReal] - posIfreq[iImag]*iZ[iImag])*factor;
        }
        
        /* Compute inverse FFT of V(f) to get V(t) */
        realFFT(Vfreq, nb, INVERSE_FFT);
        Vtime = Vfreq;
        
        /* change particle transverse momenta to reflect voltage in relevant bin */
        applyTransverseWakeKicks(part+ip1, time+ip1, pz, pbin, npb, 
                                 Po, plane, 
                                 Vtime, nb, tmin, dt, ztransverse->interpolate,
                                 plane==0?ztransverse->xProbeExponent:ztransverse->yProbeExponent);
      }

      if (ztransverse->SDDS_wake_initialized && ztransverse->wakes) {
        /* wake potential output */
        factor = ztransverse->macroParticleCharge*particleRelSign/dt;
        if ((ztransverse->wake_interval<=0 || ((i_pass0-ztransverse->wake_start)%ztransverse->wake_interval)==0) &&
            i_pass0>=ztransverse->wake_start && i_pass0<=ztransverse->wake_end) {
          if (first && !SDDS_StartTable(&ztransverse->SDDS_wake, nb)) {
            SDDS_SetError("Problem starting SDDS table for wake output (track_through_ztransverse)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          for (ib=0; ib<nb; ib++) {
            if (!SDDS_SetRowValues(&ztransverse->SDDS_wake, SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE, ib,
                                   0, ib*dt, 
                                   1+plane*2, posItime[plane][ib]*factor,  
                                   2+plane*2, Vtime[ib], -1)) {
              SDDS_SetError("Problem setting rows of SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (!SDDS_SetParameters(&ztransverse->SDDS_wake, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                  "Pass", i_pass0, "q", ztransverse->macroParticleCharge*particleRelSign*np, NULL)) {
            SDDS_SetError("Problem setting parameters of SDDS table for wake output (track_through_ztransverse)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (ztransverse->broad_band) {
            if (!SDDS_SetParameters(&ztransverse->SDDS_wake, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                    "Rs", ztransverse->Rs, "fo", ztransverse->freq, 
                                    "Deltaf", ztransverse->bin_size, NULL)) {
              SDDS_SetError("Problem setting parameters of SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (!first) {
            if (!SDDS_WriteTable(&ztransverse->SDDS_wake)) {
              SDDS_SetError("Problem writing SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            if (!inhibitFileSync)
              SDDS_DoFSync(&ztransverse->SDDS_wake);
          }
        }
      }
      first = 0;
    }
  }
  
#if defined(MIMIMIZE_MEMORY)
  free(posItime[0]);
  free(posItime[1]);
  free(posIfreq);
  free(Vtime);
  free(pbin);
  free(time);
  free(pz);
  posItime[0] = posItime[1] = Vtime = time = pz = posIfreq = NULL;
  pbin = NULL;
  max_n_bins = max_np = 0 ;
#endif

}
Esempio n. 8
0
int main()
{
	int choice;
	int array[MAX];
	int second_array[MAX];
	int n;
	int n1;
	int odd_occurences;
	int i = 0;
	int max_difference;

	struct pair min_max;
	int x;
	int isMajority;
	int maxSumContiguous;
	int missing;
	int searchElement;
	int searchIndex;
	int rotateBy;
	int twod[3][3];
	int j = 0;

	int sorted_array[] = {-8,1,4,6,10,45};
	int target_sum = 16;

	while(1)
	{
		printf("------------------------------------------------------------------------------------------------------\n");
		printf("1. Find the element occuring odd number of times in the array \n"); 
		printf("2. Exit \n"); 
		printf("3. Find the union of two arrays \n"); 
		printf("4. Find the intersection of two sorted arrays \n"); 
		printf("5. Find the maximum difference between two elements in an array \n");
		printf("6. Separate into zeroes and ones in a binary array of one dimentsion \n");
		printf("7. Find the minimum and maximum elements of the array \n");
		printf("8. Check for majority element in the array \n"); 
		printf("9. Find the first and the second smallest element in an array \n"); 
		printf("10. Find all the elements in the araay which have all the elements on the right which are lesser than the element \n"); 
		printf("11. Largest sum contiguous sub array \n");
		printf("12. Find the missing number among n contiguous elements in an array \n"); 
		printf("13. Find an element in a rotated sorted array(find element in this array 4567123) \n"); 
		printf("14. Reverse the array \n");
		printf("15. Left rotate an array \n"); 
		printf("16. If an element in a matrix make the corresponding row and column as zero \n");
		printf("17. Given a sorted array and a target integer find two elements of the array whose sum equals the target integer \n");
		printf("18. Right rotate an array \n"); 
		printf("------------------------------------------------------------------------------------------------------\n");

		printf("Enter the choice \n");
		scanf("%d", &choice);

		switch(choice)
		{
			case 1:
					printf("Enter the number of elements of the array \n");
					scanf("%d", &n);

					printf("Enter the elements of the array \n");
					for(i = 0 ; i < n ; i++)
					{
						scanf("%d", &array[i]);
					}
					odd_occurences =  find_odd_occurence(array,n);
					printf("The element occuring odd number of times is %d \n", odd_occurences);
					break;

			case 2:
					exit(1);

			case 3:
					printf("Enter the number of elements of the array1 \n");
					scanf("%d",&n);

					printf("Enter the elements of the array 1 \n");
					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}


					printf("Enter the number of elements of the array2 \n");
					scanf("%d", &n1);

					printf("Enter the elements of the array 2 \n");
					for(i = 0; i < n1; i++)
					{
						scanf("%d",&second_array[i]);
					}

					find_union(array,n,second_array,n1);
					break;

			case 4:
					printf("Enter the number of elements of the array1 \n");
					scanf("%d",&n);

					printf("Enter the elements of the array 1 \n");
					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}


					printf("Enter the number of elements of the array2 \n");
					scanf("%d", &n1);

					printf("Enter the elements of the array 2 \n");
					for(i = 0; i < n1; i++)
					{
						scanf("%d",&second_array[i]);
					}

					find_intersection(array,n,second_array,n1);
					break;

			case 5:
					printf("Enter the number of elements of the array \n");
					scanf("%d", &n);
					printf("Enter the elements of the array \n");

					for(i = 0 ; i < n; i++)
					{
						scanf("%d", &array[i]);
					}

					max_difference = find_max_difference(array,n);
					printf("The maximum difference in the array %d \n", max_difference);
					break;

			case 6:
					printf("Enter the number of elements of the array \n");
					scanf("%d",&n);
					printf("Enter the elements of the array \n");

					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					separate_into_zeroes_ones(array,n);
					display(array,n);
					break;

			case 7:
					printf("Enter the number of elements of the array \n");
					scanf("%d", &n);
					printf("Enter the elements of the array \n");

					for(i = 0 ; i < n; i++)
					{
						scanf("%d", &array[i]);
					}

					min_max =  find_min_max(array, n);
					printf("The maximum element of the array is %d \n",min_max.max);
					printf("The minimum element of the array is %d \n", min_max.min);
					break;

			case 8:
					printf("Enter the number of elements in the array \n");
					scanf("%d", &n);
					printf("Enter the element to be searched for \n");
					scanf("%d", &x);

					printf("Enter the elements of the array \n");

					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					isMajority = is_majority(array,n,x);

					if(isMajority)
					{
						printf("The element you entered is a majority element \n");

					}

					else
					{
						printf("The element you enetered is not a majority element \n");
					}

					break;

			case 9:
					printf("Enter the number of elements of the array \n");
					scanf("%d", &n);

					printf("Enter the elements of the array one by one \n");
					for(i = 0 ; i < n; i++)
					{
						scanf("%d", &array[i]);
					}

					find_first_second_smallest(array,n);
					break;

			case 10:
					printf("Enter the number of elements of the array \n");
					scanf("%d",&n);

					printf("Enter the elements of the array \n");
					for(i = 0; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					find_leader(array,n);

					break;

			case 11:

					printf("Enter the number of elements of the array \n");
					scanf("%d",&n);
					printf("Enter the elements of the array \n");
					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					maxSumContiguous = find_largest_sum_contiguous(array,n);
					printf("The maximum sum is %d \n",maxSumContiguous);
					break;

			case 12:
					printf("Enter the number of elements of the array \n");
					scanf("%d", &n);
					printf("Enter the elements of the array \n");
					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					missing = find_missing_number(array,n);
					printf("The missing number is %d \n", missing);


					break;

			case 13:
					printf("Enter the number of elements of the array \n");
					scanf("%d",&n);

					printf("Enter the elements of the array \n");
					for(i = 0 ; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					printf("Enter the search element \n");
					scanf("%d",&searchElement);

					searchIndex = find_element_in_rotated(array,n,searchElement);
					if(searchIndex != -1)
					{
						printf("The element is found in the array at %d \n",searchIndex);
					}

					else
					{
						printf("The element is not found in the array \n");
					}

					break;

			case 14:
					printf("Enter the number of elements of the array \n");
					scanf("%d",&n);
					
					printf("Enter the elements of the array \n");
					for(i = 0; i < n; i++)
					{
						scanf("%d",&array[i]);
					}

					reverse(array,0,n-1);
					display(array,n);
					break;

			case 15:
					printf("Enter the number of elements of the array \n");
					scanf("%d",&n);
					printf("Enter the elements of the array \n");
					for(i = 0; i <n; i++)
					{
						scanf("%d",&array[i]);
					}

					printf("Enter the number of elements by which the array has to be rotated \n");
					scanf("%d",&rotateBy);
					rotate(array,rotateBy,n);
					display(array,n);
					break;


			case 16:
					
					printf("Enter the elements of the array \n");
					for(i = 0; i < 3; i++)
					{
						for(j = 0; j < 3; j++)
						{
							scanf("%d",&twod[i][j]);
						}
					}

					printf("This is from main \n");
					for(i = 0; i < 3; i++)
					{
						for(j = 0; j < 3; j++)
						{
							printf("%d \t",twod[i][j]);
						}

						printf("\n");
					}

					make0rows0columns(twod);

					break;

			case 17:

					findTwoElementsTarget(sorted_array,target_sum,6);
					break;

			case 18:
					printf("Enter the number of elements of the array \n");
					scanf("%d", &n);
					printf("Enter the elements of the array \n");
					for(i = 0; i <n; i++)
					{
						scanf("%d",&array[i]);
					}

					printf("Enter the number of elements by which the array has to be rotated \n");
					scanf("%d",&rotateBy);
					right_rotate(array,rotateBy, n);
					display(array,n);
					break;
			default:
					break;




		}

	}
}
Esempio n. 9
0
void fill_t::checkerboard_fill(point_t p,float width,float height){
	int minx=p.getX();
	int miny=p.getY();
	int maxx=p.getX();
	int maxy=p.getY();
	find_min_max(p,miny,maxy,minx,maxx,width,height);

	std::queue <point_t> fillQueue;
	fillQueue.push(p);
	float pointx=p.getX();
	float pointy=p.getY();
	color_t c=colorArray[(int)pointx][(int)pointy];
	
    color_t pixels;
    float trans_x,trans_y;
    while(!fillQueue.empty()){
    	// std::cout<<c.getR()<<" ANSSS"<<std::endl;
    	// exit(0);
		p=fillQueue.front();
		pointx=p.getX();
		pointy=p.getY();
		fillQueue.pop();
		
		//Added Canvas size check
		if(pointx>=width || pointy>=height || pointx<0 || pointy<0)
			continue;
		//glReadPixels(pointx,pointy,1.0,1.0,GL_RGB,GL_FLOAT,pixels);
		pixels = colorArray[(int)pointx][(int)pointy];
		
		if( (pixels.getR()==c.getR()) && (pixels.getG()==c.getG()) && (pixels.getB()==c.getB()) )
		{
			point_t p1(pointx, pointy);
			trans_x=pointx-minx;
			trans_y=pointy-miny;
			if((((int)trans_x/16)%2)==0){
				if((((int)trans_y/16)%2)==0){
					p1.draw(pen_t(color1,1));
				}
				else{
					p1.draw(pen_t(color2,1));
				}
			}
			else{
				if((((int)trans_y/16)%2)==0){
					p1.draw(pen_t(color2,1));
				}
				else{
					p1.draw(pen_t(color1,1));
				}
			}
			
			
			fillQueue.push(point_t(pointx+1,pointy));
			fillQueue.push(point_t(pointx,pointy+1));
			fillQueue.push(point_t(pointx-1,pointy));
			fillQueue.push(point_t(pointx,pointy-1));
		}
		
	}
	
}
Esempio n. 10
0
int main(int argc, char **argv)
{
    double tolerance, result;
    long nEval;
    int32_t nEvalMax = 5000, nPassMax = 25;
    double a[4], da[4];
    double alo[4], ahi[4];
    long n_dimen = 4, zeroes;
    SDDS_DATASET InputTable, OutputTable;
    SCANNED_ARG *s_arg;
    long i_arg, i, clue, fullOutput;
    char *input, *output, *xName, *yName;
    int32_t xIndex, yIndex, fitIndex, residualIndex;
    long retval;
    double *fitData, *residualData, rmsResidual;
    unsigned long guessFlags, dummyFlags, pipeFlags;
    double constantGuess, factorGuess, freqGuess, phaseGuess;
    double firstZero, lastZero;
    unsigned long simplexFlags = 0;
    
    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&s_arg, argc, argv);
    if (argc<2 || argc>(2+N_OPTIONS))
        bomb(NULL, USAGE);

    input = output = NULL;
    tolerance = 1e-6;
    verbosity = fullOutput = 0;
    clue = -1;
    xName = yName = NULL;
    guessFlags = 0;
    pipeFlags = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_TOLERANCE:
                if (s_arg[i_arg].n_items!=2 || sscanf(s_arg[i_arg].list[1], "%lf", &tolerance)!=1)
                    SDDS_Bomb("incorrect -tolerance syntax");
                break;
              case SET_VERBOSITY:
                if (s_arg[i_arg].n_items!=2 || sscanf(s_arg[i_arg].list[1], "%ld", &verbosity)!=1)
                    SDDS_Bomb("incorrect -verbosity syntax");
                break;
              case SET_GUESS:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("incorrect -guess syntax");
                s_arg[i_arg].n_items -= 1;
                if (!scanItemList(&guessFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                    "constant", SDDS_DOUBLE, &constantGuess, 1, GUESS_CONSTANT_GIVEN,
                                    "factor", SDDS_DOUBLE, &factorGuess, 1, GUESS_FACTOR_GIVEN,
                                    "frequency", SDDS_DOUBLE, &freqGuess, 1, GUESS_FREQ_GIVEN,
                                    "phase", SDDS_DOUBLE, &phaseGuess, 1, GUESS_PHASE_GIVEN,
                                    NULL))
                    SDDS_Bomb("invalid -guess syntax");
                break;
              case SET_COLUMNS:
                if (s_arg[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -columns syntax");
                xName = s_arg[i_arg].list[1];
                yName = s_arg[i_arg].list[2];
                break;
              case SET_FULLOUTPUT:
                fullOutput = 1;
                break;
              case SET_LIMITS:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("incorrect -limits syntax");
                s_arg[i_arg].n_items -= 1;
                if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                    "evaluations", SDDS_LONG, &nEvalMax, 1, 0,
                                    "passes", SDDS_LONG, &nPassMax, 1, 0,
                                    NULL) ||
                    nEvalMax<=0 || nPassMax<=0)
                    SDDS_Bomb("invalid -limits syntax");
                break;
              case SET_PIPE:
                if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
                    SDDS_Bomb("invalid -pipe syntax");
                break;
              default:
                fprintf(stderr, "error: unknown/ambiguous option: %s\n", s_arg[i_arg].list[0]);
                exit(1);
                break;
                }
            }
        else {
            if (input==NULL) 
                input = s_arg[i_arg].list[0];
            else if (output==NULL)
                output = s_arg[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }

    processFilenames("sddssinefit", &input, &output, pipeFlags, 0, NULL);

    if (!xName || !yName)
        SDDS_Bomb("-columns option must be given");

    if (!SDDS_InitializeInput(&InputTable, input) ||
        SDDS_GetColumnIndex(&InputTable, xName)<0 || SDDS_GetColumnIndex(&InputTable, yName)<0)
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

    setupOutputFile(&OutputTable, &xIndex, &yIndex, &fitIndex, &residualIndex, output, fullOutput,
                    &InputTable, xName, yName);

    fitData = residualData = NULL;

    alo[0] = - (ahi[0] = DBL_MAX);
    alo[1] = alo[2] = 0;
    ahi[1] = ahi[2] = DBL_MAX;
    alo[3] = - (ahi[3] = PIx2);
    firstZero = lastZero = 0;
    while ((retval=SDDS_ReadPage(&InputTable))>0) {
        if (!(xData = SDDS_GetColumnInDoubles(&InputTable, xName)) ||
            !(yData = SDDS_GetColumnInDoubles(&InputTable, yName)))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if ((nData = SDDS_CountRowsOfInterest(&InputTable))<4)
            continue;

        find_min_max(&yMin, &yMax, yData, nData);
        find_min_max(&xMin, &xMax, xData, nData);
        zeroes = 0;
        for (i=1; i<nData; i++)
          if (yData[i]*yData[i-1]<=0) {
            i++;
            if (!zeroes)
              firstZero = (xData[i]+xData[i-1])/2;
            else 
              lastZero = (xData[i]+xData[i-1])/2;
            zeroes ++;
          }
        a[0] = (yMin+yMax)/2;
        a[1] = (yMax-yMin)/2;
        if (!zeroes)
            a[2] = 2/fabs(xMax-xMin);
        else
            a[2] = zeroes/(2*fabs(lastZero-firstZero));
        a[3] = 0;

        if (guessFlags&GUESS_CONSTANT_GIVEN)
            a[0] = constantGuess;
        if (guessFlags&GUESS_FACTOR_GIVEN)
            a[1] = factorGuess;
        if (guessFlags&GUESS_FREQ_GIVEN)
            a[2] = freqGuess;
        if (guessFlags&GUESS_PHASE_GIVEN)
            a[3] = phaseGuess;

        alo[1] = a[1]/2;
        if (!(da[0] = a[0]*0.1))
          da[0] = 0.01;
        if (!(da[1] = a[1]*0.1))
          da[1] = 0.01;
        da[2] = a[2]*0.25;
        da[3] = 0.01;

        nEval = simplexMin(&result, a, da, alo, ahi, NULL, n_dimen, -DBL_MAX, tolerance, fitFunction, 
                            (verbosity>0?report:NULL), nEvalMax, nPassMax,
                           12, 3, 1.0, simplexFlags);
        
        fitData = trealloc(fitData, sizeof(*fitData)*nData);
        residualData = trealloc(residualData, sizeof(*residualData)*nData);
        for (i=result=0; i<nData; i++)
            result += sqr(residualData[i] = yData[i]-(fitData[i]=a[0]+a[1]*sin(PIx2*a[2]*xData[i]+a[3])));
        rmsResidual = sqrt(result/nData);
        if (verbosity>1) {
            fprintf(stderr, "RMS deviation: %.15e\n", rmsResidual);
            fprintf(stderr, "(RMS deviation)/(largest value): %.15e\n", rmsResidual/MAX(fabs(yMin), fabs(yMax)));
            }
        if (verbosity>0) {
            fprintf(stderr, "coefficients of fit to the form y = a0 + a1*sin(2*PI*a2*x+a3), a = \n");
            for (i=0; i<4; i++)
                fprintf(stderr, "%.8e ", a[i]);
            fprintf(stderr, "\n");
            }

        if (!SDDS_StartPage(&OutputTable, nData) ||
            !SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, xData, nData, xIndex) ||
            !SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, fitData, nData, fitIndex) ||
            !SDDS_SetParameters(&OutputTable, SDDS_PASS_BY_VALUE|SDDS_SET_BY_NAME,
                                "sinefitConstant", a[0], "sinefitFactor", a[1], "sinefitFrequency", a[2], 
                                "sinefitPhase", a[3], "sinefitRmsResidual", rmsResidual, NULL) ||
            (fullOutput && 
             (!SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, yData, nData, yIndex) ||
              !SDDS_SetColumn(&OutputTable, SDDS_SET_BY_INDEX, residualData, nData, residualIndex) )) ||
            !SDDS_WritePage(&OutputTable))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
    return 0;
    }
Esempio n. 11
0
void Vectorizer::process_solution(MeshFunction* xsln, int xitem, MeshFunction* ysln, int yitem, double eps)
{
  // sanity check
  if (xsln == NULL || ysln == NULL) error("One of the solutions is NULL in Vectorizer:process_solution().");


  lock_data();
  TimePeriod cpu_time;

  // initialization
  this->xsln = xsln;
  this->ysln = ysln;
  this->xitem = xitem;
  this->yitem = yitem;
  this->eps = eps;
  nv = nt = ne = nd = 0;
  del_slot = -1;

  Mesh* meshes[2] = { xsln->get_mesh(), ysln->get_mesh() };
  if (meshes[0] == NULL || meshes[1] == NULL) {
    error("One of the meshes is NULL in Vectorizer:process_solution().");
  }

  Transformable* fns[2] = { xsln, ysln };
  Traverse trav;

  // estimate the required number of vertices and triangles
  // (based on the assumption that the linear mesh will be
  // about four-times finer than the original mesh).
  int nn = meshes[0]->get_num_elements() + meshes[1]->get_num_elements();
  int ev = std::max(32 * nn, 10000);
  int et = std::max(64 * nn, 20000);
  int ee = std::max(24 * nn, 7500);
  int ed = ee;

  lin_init_array(verts, double4, cv, ev);
  lin_init_array(tris, int3, ct, et);
  lin_init_array(edges, int3, ce, ee);
  lin_init_array(dashes, int2, cd, ed);

  info = (int4*) malloc(sizeof(int4) * cv);

  // initialize the hash table
  int size = 0x1000;
  while (size*2 < cv) size *= 2;
  hash_table = (int*) malloc(sizeof(int) * size);
  memset(hash_table, 0xff, sizeof(int) * size);
  mask = size-1;


  // select the linearization quadrature
  Quad2D *old_quad_x, *old_quad_y;
  old_quad_x = xsln->get_quad_2d();
  old_quad_y = ysln->get_quad_2d();

  xsln->set_quad_2d((Quad2D*) &quad_lin);
  ysln->set_quad_2d((Quad2D*) &quad_lin);

  if (!xitem) error("Parameter 'xitem' cannot be zero.");
  if (!yitem) error("Parameter 'yitem' cannot be zero.");
  get_gv_a_b(xitem, xia, xib);
  get_gv_a_b(yitem, yia, yib);
  if (xib >= 6) error("Invalid value of paremeter 'xitem'.");
  if (yib >= 6) error("Invalid value of paremeter 'yitem'.");

  max = 1e-10;
  trav.begin(2, meshes, fns);
  Element** e;
  while ((e = trav.get_next_state(NULL, NULL)) != NULL)
  {
    xsln->set_quad_order(0, xitem);
    ysln->set_quad_order(0, yitem);
    scalar* xval = xsln->get_values(xia, xib);
    scalar* yval = ysln->get_values(yia, yib);

    for (unsigned int i = 0; i < e[0]->nvert; i++)
    {
      double fx = getvalx(i);
      double fy = getvaly(i);
      if (fabs(sqrt(fx*fx + fy*fy)) > max) max = fabs(sqrt(fx*fx + fy*fy));
    }
  }
  trav.finish();

  trav.begin(2, meshes, fns);
  // process all elements of the mesh
  while ((e = trav.get_next_state(NULL, NULL)) != NULL)
  {
    xsln->set_quad_order(0, xitem);
    ysln->set_quad_order(0, yitem);
    scalar* xval = xsln->get_values(xia, xib);
    scalar* yval = ysln->get_values(yia, yib);

    double* x = xsln->get_refmap()->get_phys_x(0);
    double* y = ysln->get_refmap()->get_phys_y(0);

    int iv[4];
    for (unsigned int i = 0; i < e[0]->nvert; i++)
    {
      double fx = getvalx(i);
      double fy = getvaly(i);
      iv[i] = create_vertex(x[i], y[i], fx, fy);
    }

    // we won't bother calculating physical coordinates from the refmap if this is not a curved element
    curved = (e[0]->cm != NULL);

    // recur to sub-elements
    if (e[0]->is_triangle())
      process_triangle(iv[0], iv[1], iv[2], 0, NULL, NULL, NULL, NULL, NULL);
    else
      process_quad(iv[0], iv[1], iv[2], iv[3], 0, NULL, NULL, NULL, NULL, NULL);

    // process edges and dashes (bold line for edge in both meshes, dashed line for edge in one of the meshes)
    Trf* xctm = xsln->get_ctm();
    Trf* yctm = ysln->get_ctm();
    double r[4] = { -1.0, 1.0, 1.0, -1.0 };
    double ref[4][2] = { {-1.0,-1.0}, {1.0,-1.0}, {1.0,1.0}, {-1.0,1.0} };
    for (unsigned int i = 0; i < e[0]->nvert; i++)
    {
      bool bold = false;
      double px = ref[i][0];
      double py = ref[i][1];
      // for odd edges (1, 3) we check x coordinate after ctm transformation, if it's the same (1 or -1) in both meshes => bold
      if (i & 1) {
        if ((xctm->m[0]*px + xctm->t[0] == r[i]) && (yctm->m[0]*px + yctm->t[0] == r[i]))
          bold = true;
      }
      // for even edges (0, 4) we check y coordinate after ctm transformation, if it's the same (-1 or 1) in both meshes => bold
      else {
        if ((xctm->m[1]*py + xctm->t[1] == r[i]) && (yctm->m[1]*py + yctm->t[1] == r[i]))
          bold = true;
      }
      int j = e[0]->next_vert(i);
      // we draw a line only if both edges lies on the boundary or if the line is from left top to right bottom
      if (((e[0]->en[i]->bnd) && (e[1]->en[i]->bnd)) ||
         (verts[iv[i]][1] < verts[iv[j]][1]) ||
         (verts[iv[i]][1] == verts[iv[j]][1] && verts[iv[i]][0] < verts[iv[j]][0]))
      {
        if (bold)
          process_edge(iv[i], iv[j], e[0]->en[i]->marker);
        else
          process_dash(iv[i], iv[j]);
      }
    }
  }
  trav.finish();

  find_min_max();

  verbose("Vectorizer created %d verts and %d tris in %0.3g s", nv, nt, cpu_time.tick().last());
  //if (verbose_mode) print_hash_stats();
  unlock_data();

   // select old quadratrues
  xsln->set_quad_2d(old_quad_x);
  ysln->set_quad_2d(old_quad_y);

  // clean up
  ::free(hash_table);
  ::free(info);

}