Question

In: Computer Science

Are my codes correct? #include <iostream> #include <string> #include <cassert> #include <cctype> #include <cstring> #include <stdio.h>...

Are my codes correct?

#include <iostream>
#include <string>

#include <cassert>

#include <cctype>

#include <cstring>

#include <stdio.h>

#include <ctype.h>

#include<fstream>

int locateMinimum( const std::string array[ ], int n ){

   if(n <= 0){

   return -1;

   }

   else{

   int minInd = 0;

   for(int i = 0; i < n; ++i){

   if(array[i] < array[minInd]){

   minInd = i;

   }

   }

   return minInd;

   }

}

int countPunctuation( const std::string array[], int n)

{

int count = 0;

for (int i=0;i<= n;i++)

{

if (array[i]== ('!', ',' ,':' ,';' ,'.', '-' ,'?'))

{

count = count + 1;

return count;

}

else {

return 0;

}

bool hasReverse(const std::string array[ ], int n )

{

   // entire array

   for(int i=0;i<n;i++)

   {

   //finding the reverse of the string

   string rev = string(array[i].rbegin(),array[i].rend());

   //checking that reverse of the string is present in the array or not

   //if present returning true or we are returning false

   for(int j=0;j<n;j++)

   {

   if(array[j] == rev){

   return true;

   }

   }

   }

   return false;

   }

char highestOccurredCharacter(const std::string array[ ], int n, int index ){

if( n <= 0 || index >= n || index < 0) //if invalid array length n or invalid index is given the function returns null character

return '\0';

int highest=0; //initially considering the highest to be 0

char c = '\0'; //to save the most repeating character

for(int i=0;i<array[index].length();i++){ //traversing through the string array[index]

int count = 0; //initial count of character array[index][i] is 0

for(int j=0;j<array[index].length();j++) //traversing through the string array[index] again to find the count of repeatetions of array[index][i] character

if(array[index][i]==array[index][j])

count++;

if(count>highest){ //if count is greater than the highest count then we have a new highest which has to be stored in highest

highest = count; //save the latest highest in highest

c = array[index][i]; //save the character of latest highest in c

}

}

return c; //return the total highest repeated character

}

bool isInIncreasingOrder( const std::string array[ ], int n )

{

if(n < 0){

return false;

}

else if(n == 0){

return true;

}

else{

for(int i = 1; i < n; ++i){

if(fruit[i] <= fruit[i - 1]){

return false;

}

}

return true;

}

}

char firstNonRepeatedCharacter(const std::string array[ ], int n, int index);

   //This function finds out the first non repeating chracter and returns it

if( n <= 0 || index>= n || index < 0) { //if invalid array length n or invalid index is given the function returns null character

return '\0';}

for(int i=0;i<array[index].length();i++){ //traversing through the string array[index] chracters

int count = 0; //initialising count to 0 initially

for(int j=0;j<array[index].length();j++) //traversing through the string array[index] chracters to count the occurrences

if(array[index][i]==array[index][j]) //

count++;

if(count==1) //the count of non Repeating Character is 1 so if any chracter gets a count 1 it must be returned and it would be the firstNonRepeatedCharacter

return array[index][i];

}

bool isOnlyDigits( const std::string array[ ], int n ){

//traversing array

for(int i=0;i<n;i++)

{

//traversing each string of the array

for(int j=0;j<array[i].length();j++)

{

//checking the string contains only digits or not if not we are returning false

if (!(array[i][j] >= '0' && array[i][j] <= '9'))

return false;

}

}

return true;

}

}

Solutions

Expert Solution

  • The method locateMinimum() is correct. But you can start the loop from i = 1 rather than i = 0, because minInd is already set as 0 and you don't need to compare array[0] with array[0] again.
  • countPunctuation is incorrect.
    1. You cannot compare string with characters. array[i] is a string, it cannot be compared to '?'.
    2. The commad operator returns the last value. Which means everytime you are doing, "array[i]== ('!', ',' ,':' ,';' ,'.', '-' ,'?')", it's the same as "array[i] == '?'", which is again not a valid operation (refer to point 1)
    3. To check if a value is equal to one value in a seperate values, you need to check for equality with each element in the set and combine all of them using the logical OR (||) operator.
    4. To count the number of punctuations, you need to traverse through each character in each array. Here's the corrected code:

int countPunctuation(const std::string array[], int n) {

    int count = 0;

    for(int i = 0; i < n; i++) {

        for(int j = 0; j < array[i].length(); j++) {

            if(array[i][j] == '!' || array[i][j] == ',' || array[i][j] == ':' || array[i][j] == ';' || array[i][j] == '-' || array[i][j] == '?')

                count++;

        }

    }

    return count;

}

  • hasReverse() has a small logical error. Instead of returning true when you have a string in the array which is the same as its reverse, you want to return false when you find one that is not a pallindrome. What this will do, is you will say you have found one non-pallindromic string, which means all strings in the array are not pallindromic. Otherwise if you have checked all the strings and they are all pallindromes, then you just return false, because all are pallindromic. Here's the corrected code:

bool hasReverse(const std::string array[], int n) {

    for(int i = 0; i < n; i++) {

        string rev = string(array[i].rbegin(),array[i].rend());

        if(array[i] != rev)

            return false;

    }

    return true;

}

  • highestOccurredCharacter() is correct. Keep in mind though, that this has an O(n2) complexity and is a brute force solution. You can have a linear time O(n) solution if you use some more space. By that I mean you can use a HashMap to count the occurences of each character use it to find the one with the higesht occurence.
  • isInIncreasingOrder() is correct for a strictly increasing constraint. For a more relaxed constraint (two equal elements can be place one after the other) which is not strictly increasing just use the less than operator instead of a less than equal to operator.
  • firstNonRepeatedCharacter() is correct. This can be further optimized though.
  • isOnlyDigits() is correct. This will run perfectly.

Related Solutions

C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using namespace std; const int CWIDTH = 26; int main() {    int choice;    double convertFoC, converCtoF;    double starting, endvalue, incrementvalue;    const int CWIDTH = 13;    do {       cin >> choice;    switch (choice)    {        cin >> starting;    if (starting == 28){       cout << "Invalid range. Try again.";    }    while (!(cin >> starting)){       string  garbage;       cin.clear();       getline(cin, garbage);       cout << "Invalid data Type, must be a number....
A C++ question: I want to indent the code of this C++ program: #include<iostream> #include<cstring> using...
A C++ question: I want to indent the code of this C++ program: #include<iostream> #include<cstring> using namespace std; int lastIndexOf(char *s, char target) { int n=strlen(s); for(int i=n-1;i>=0;i--) { if(s[i]==target) { return i; } } return -1; } void reverse(char *s) { int n=strlen(s); int i=0,j=n-1; while(i<=j) { char temp=s[i]; s[i]=s[j]; s[j]=temp; i++; j--; } return; } int replace(char *s, char target, char replacementChar) { int len=strlen(s); int total=0; for(int i=0;i<len;i++) { if(s[i]==target) { s[i]=replacementChar; total+=1; } } return total;...
#include "pch.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main() {        FILE...
#include "pch.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main() {        FILE *fp;        char c;        errno_t err;        err = 0;        err = fopen_s(&fp,"Desktop/test.txt", "r"); file is on my desktop but I err=2 but I don't think it is opening the file?        printf("%d\n", err);        if (err == 2)        {            printf("The file was opened\n");            while (1)       ...
*****MUST ONLY USE****** #include <iostream> #include <fstream> #include <string.h> #include <stdio.h> Description The word bank system...
*****MUST ONLY USE****** #include <iostream> #include <fstream> #include <string.h> #include <stdio.h> Description The word bank system maintains all words in a text file named words.txt. Each line in the text file stores a word while all words are kept in an ascending order. You may assume that the word length is less than 20. The system should support the following three functions: Word lookup: to check whether a given word exists in the word bank. Word insertion: to insert a...
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string userInput; getline(cin, userInput);...
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string userInput; getline(cin, userInput); // Declaring base int N = 30; if (userInput.length() > 10) { cout << 0 << endl; } else { int finalTotal = 0; //Iterates through userInput for(int i = 0; i < 10; i++){ char convertedInput = userInput[i]; // ASCII decimal value of each character int asciiDec = int(convertedInput); //Casts char value from input to int value stringstream chr; chr << convertedInput; int...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits>...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits> #include <vector> using namespace std; // // CLASS: NODE // class Node{ public: int value = 0; // our node holds an integer Node *next = nullptr; // our node has a pointer to the next Node Node(int i){ // contructor for our Node class value = i; // store a copy of argument "i" in "value" next = nullptr; // be sure next...
Can anyone change it to double linked list #include<stdio.h> #include<stdlib.h> #include <iostream> using namespace std; struct...
Can anyone change it to double linked list #include<stdio.h> #include<stdlib.h> #include <iostream> using namespace std; struct Node {     int data;     struct Node* next; }; void printMiddle(struct Node *head) {     struct Node *slow_ptr = head;     struct Node *fast_ptr = head;     if (head!=NULL)     {         while (fast_ptr != NULL && fast_ptr->next != NULL)         {             fast_ptr = fast_ptr->next->next;             slow_ptr = slow_ptr->next;         }         printf("The middle element is [%d]\n\n", slow_ptr->data);     } } void...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
#include <iostream> #include <string> #include <vector> using namespace std; class Song{ public: Song(); //default constructor Song(string...
#include <iostream> #include <string> #include <vector> using namespace std; class Song{ public: Song(); //default constructor Song(string t, string a, double d); //parametrized constructor string getTitle()const; // return title string getAuthor()const; // return author double getDurationMin() const; // return duration in minutes double getDurationSec() const; // return song's duration in seconds void setTitle(string t); //set title to t void setAuthor(string a); //set author to a void setDurationMin(double d); //set durationMin to d private: string title; //title of the song string author;...
C++ The txt file is not showing up in my output #include <iostream> #include <fstream> #include...
C++ The txt file is not showing up in my output #include <iostream> #include <fstream> #include <string> #include "Classroom.h" using namespace std; Classroom myLib; void loadDataset(string fileName) { ifstream myFile; myFile.open(fileName.c_str()); } void continueMessage(string message) { cout << message << endl; cout << "Press Enter to continue.." << endl; cin.get(); } int main() { string fileName = "dataset.txt"; loadDataset(fileName); myLib.print(); continueMessage; string ID = "Janet Newman"; myLib.removeStudent (ID); continueMessage("Janet Newman has been removed."); //--------------------------------------------------------------------------- myLib.print(); continueMessage("All students are listed!"); return...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT