vendredi 29 juillet 2016

Lexicographic Order in Multidimensional Array C++

I'm having trouble with one final task that my program should do. Having my output character in a lexicographic order.

For example, if I input bbbaaa it should have an output of

Frequencies: a 3 b 3

Not

Frequencies: b 3 a 3

Can anyone help me solve this problem? Here is my code:

#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>

using namespace std;

void sort(char letters[], int integers[], int size);
void swap_letters(char& first, char& second, int& int1, int& int2);
int index_of_largest(const int integers[], int start_index, int number_used);

int main(){
  const int MAX_CHARS = 200;
  char letters[MAX_CHARS] = {'\0'};
  int integers[MAX_CHARS] = {'\0'};
  int index, size = 0;
  char character;

  cout << "Enter text:" << endl;
  cin.get(character);
  character = tolower(character);
  while (character!= '.' && size < MAX_CHARS){
    if(isalpha(character)){
      index = 0;
      while (index < size){
        if(letters[index] == character)
          break;
        else
          index++;
      }
      if (index < size){
        integers[index] = integers[index] + 1;
      }
      else{
        letters[index] = character;
        integers[index] = 1;
        size++;
      }
    }
    cin.get(character);
    character = tolower(character);
  }
  letters[index] = tolower(letters[index]);
  sort(letters, integers, size);

  cout << "Frequencies:"<< endl;

  for(int i = 0; i < size; i++){
    cout << letters[i]  << " " << integers[i] << endl;
  }
  return 0;
}

void sort(char letters[], int integers[], int size){
    for (int i = 0; i < size -1; i++){
      int j = index_of_largest(integers, i, size);
      swap_letters(letters[i], letters[j], integers[i], integers[j]);
  }
}
void swap_letters(char& first, char& second, int& int1, int& int2){
  char temp_char = first;
  first = second;
  second = temp_char;
  int temp_int = int1;
  int1 = int2;
  int2 = temp_int;
}
int index_of_largest(const int integers[], int start_index, int number_used){
  int max_int = integers[start_index];
  int max_int_index = start_index;
  for (int index = start_index + 1; index < number_used; index++){
    if (integers[index] > max_int){
      max_int = integers[index];
      max_int_index = index;
    }
  }
  return max_int_index;
}

Aucun commentaire:

Enregistrer un commentaire