I am having trouble applying the insertion sort algorithm to the string because it. I have been getting various errors which I think are from issues regarding strings vs char types.
Ex:
candidate template ignored: could not match 'stack' against 'basic_string'
operator> (const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
The insertion sort algorithm was pulled from geeks for geeks but I just changed it to string array.
void insertionSort(string arr[], int n)
{
int i, key, j, unsortedness;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main()
{
//Read in from file stuff missing to save space
int d, lengthStrings, numberStrings; // D will hold the number of data sets
infile >> d;
cout << d << endl;
while (d != 0)
{
infile >> lengthStrings;
infile >> numberStrings;
int numCopy = numberStrings;
int i = 0;
string arrayDna[numberStrings]; //char arrayDna[numberStrings][lengthStrings] instead?;
while (numberStrings != 0)
{
infile >> arrayDna[i];
i++;
numberStrings--;
}
insertionSort(arrayDna[], numCopy);
for (int i = 0; i < numCopy; i++)
cout << arrayDna[i] << "\n";
d--;
So basically I need help fixing the error not allowing me to apply this insertion algorithm to my own string array.
I didn't work on the logic, but cleared all the basic errors, hopefully:)
changes:
(1) arrayDna[] => arrayDna (in the parameters) while invoking insertionSort function.
(2) In the insertionSort function at line : key = arr[i],
key is an int type but needed string type, so changed type of key to string from int
void insertionSort(string arr[], int n)
{
int i,j, unsortedness;
string key;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
// Since I just need to find unsortedness and not actually sort
//I should probably just replace the two lines with something such as
//unsortedness++ and compare that way
}
arr[j + 1] = key;
}
}
int main(){
//Read in from file stuff missing to save space
int d,lengthStrings, numberStrings; // D will hold the number of data sets
infile >> d;
cout << d << endl;
while(d !=0){
infile >> lengthStrings;
infile >> numberStrings;
int numCopy=numberStrings;
int i=0;
string arrayDna [numberStrings]; //char arrayDna[numberStrings][lengthStrings] instead?;
while(numberStrings != 0){
infile >> arrayDna[i];
i++;
numberStrings--;
}
insertionSort(arrayDna, numCopy);
for (int i = 0; i < numCopy; i++)
cout << arrayDna[i] << "\n";
d--;
}
}
Related
My program is a solution for the Day 6 question in Advent of Code 2015. I get an error when I use "Start Without Debugging" and enter the puzzle input in the output window.The image contains the exact error I received. The error is related to "string subscript out of range". I would like help in resolving this error.
const int r = 1000;//global variable
const int c = 1000;//global variable
int lights[r][c];//global array
void instruction(string inp)//extracting OFF, ON, or toggle indication from the instruction
{
int* loc;
int coord[4] = { 0 };
char cond = inp[7];
loc = &coord[3];
switch (cond)
{
case 'f':
coordinates(loc, inp);
execute(coord, cond);
break;
case 'n':
coordinates(loc, inp);
execute(coord, cond);
break;
default:
coordinates(loc, inp);
execute(coord, cond);
break;
}
}
void coordinates(int* loc, string inp)//extracting coordinates from the instruction
{
int i, k = 0, l;
l = inp.length()-1;
for (i = l; inp[i] != ','; i--)
{
*loc += (inp[i]-'0') * pow(10,k);
k++;
}
i--;
loc--;
k = 0;
for (; inp[i] != ' '; i--)
{
*loc += (inp[i]-'0') * pow(10,k);
k++;
}
i = i - 9;
loc--;
k = 0;
for (; inp[i] != ','; i--)
{
*loc += (inp[i]-'0') * pow(10,k);
k++;
}
i--;
loc--;
k = 0;
for (; inp[i] != ' '; i--)
{
*loc += (inp[i]-'0') * pow(10,k);
k++;
}
}
void execute(int coord[], char cond)
{
int i, j;
for (i = coord[0]; i <= coord[2]; i++)
{
for (j = coord[1]; j <= coord[3]; j++)
{
if (cond == 'f')
lights[i][j] &= 0;
else if (cond == 'n')
lights[i][j] |= 1;
else
lights[i][j] = ~lights[i][j];
}
}
}
int main()
{
int i, j, k, count = 0;
string inp;
for (i = 0;;i++)
{
cout << "Enter an instruction" << endl;
cin >> inp;
if (inp != "xx")//To manually move to counting the number of lights turned ON
instruction(inp);
else
{
for (j = 0; j < r; j++)
{
for (k = 0; k < c; k++)
{
if (lights[j][k])
count++;
}
}
cout << endl << "Number of lights lit " << count;
break;
}
}
return 0;
}
The problem is most likely this loop (from the coordinates function):
l = inp.length()-1;
for (i = l; inp[i] != ','; i--)
{
*loc += int(inp[i]) * (10 ^ k);
k++;
}
In the very first iteration of the loop then i will be equal to l which is the length of the string, which is out of bounds.
You also don't check if you go out of bounds in the second direction (i becomes negative). You have this problem in all your loops in the coordinates function.
On another note, casting a character to int will not convert a digit character to its corresponding integer value.
Assuming ASCII encoding (the most common encoding available) then the character '2' (for example) will have the integer value 50.
Also the ^ operator it bitwise exclusive OR, not any kind of "power" or "raises" operator. It seems you could need to spend some more times with some of the basics of C++.
PROBLEM STATEMENT
You are given a strictly increasing sequence of integers A1,A2,…,AN. Your task is to compress this sequence.
The compressed form of this sequence is a sequence of ranges separated by commas (characters ','). A range is either an integer or a pair of integers separated by three dots (the string "..."). When each range a...b in the compressed form is decompressed into the subsequence (a,a+1,…,b), we should obtain the (comma-separated) sequence A again.
For each maximal contiguous subsequence (a,a+1,…,b) of A such that b≥a+2, the compressed form of A must contain the range a...b; if b≤a+1, such a sequence should not be compressed into a range. A contiguous subsequence is maximal if it cannot be extended by at least one element of A next to it. It can be proved that the compressed form of any sequence is unique (i.e. well-defined).
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one string ― the compressed form of the given sequence.
Constraints
1≤T≤100
1≤N≤100
1 ≤ Ai ≤ 1000 for each valid i
A1 < A2 < …... <AN
Subtasks
Subtask #1 (100 points): Original constraints
Example Input
3
12
1 2 3 5 6 8 9 10 11 12 15 17
4
4 5 7 8
1
4
Example Output
1...3,5,6,8...12,15,17
4,5,7,8
4
MY Code:
#include <bits/stdc++.h>
using namespace std;
bool b[1005];
int a[1005];
int main()
{
int test, i, j, size, count;
cin >> test;
while (test--)
{
for (i = 0; i < 1005; i++)
b[i] = false;
cin >> size;
for (i = 0; i < size; i++)
{
cin >> a[i];
b[a[i]] = true;
}
for (i = 0; i < 1005; i++)
{
if (b[i] == true)
{
cout << i;
j = i;
count = 0;
while (b[j] == true)
{
count++;
j++;
}
if (count > 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "..." << i - 1 << ",";
else
cout << "..." << i - 1;
}
if (count == 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "," << i - 1 << ",";
else
cout << "," << i - 1;
}
if (count == 1 && ((j - 1) != a[size - 1]))
cout << ",";
}
}
}
return 0;
}
}
MY Question:
Above code runs perfectly on my device giving desired output. But when I am submitting this solution to
Online Judge , it says segmentation fault. It's sure that fundamentally I am accessing the memory incorrectly. Could you please show me where it is?
b is defined a bool[1005]
In this part
for(i=0 ; i<4000 ; i++)
b[i] = false;
You are writing false value 4000 times, exceeding the array size.
Overwriting past the array is allowed on the compiler but will have undefined behaviour in runtime.
In short: it can or can not cause a segfault.
Here is another approach given that the input data is in a file input.txt:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
class Reader {
public:
Reader(const std::string& filename) :
filename_(std::move(filename)), is_(filename_)
{
is_.exceptions( std::ifstream::failbit | std::ifstream::badbit );
}
int get_N() {
int N;
is_ >> N;
return N;
}
std::vector<int> get_ints(int N) {
std::vector<int> v;
v.reserve(N);
for (int i = 0; i < N; i++ ) {
int value;
is_ >> value;
v.push_back(value);
}
return v;
}
int get_num_cases() {
int num_cases;
is_ >> num_cases;
return num_cases;
}
private:
std::string filename_;
std::ifstream is_;
};
bool start_range_cur( std::vector<int> &v, int j, int N )
{
if ( j>= (N - 2) ) return false;
return ((v[j+1] - v[j]) == 1) && ((v[j+2] - v[j+1]) == 1);
}
bool in_range_cur( std::vector<int> &v, int j )
{
return (v[j+1] - v[j]) == 1;
}
void print_range( int min, int max, bool print_comma)
{
std::cout << min << ".." << max;
if (print_comma) std::cout << ",";
}
void print_single(int val, bool print_comma)
{
std::cout << val;
if (print_comma) {
std::cout << ",";
}
}
int main() {
Reader is {"input.txt"};
int num_cases = is.get_num_cases();
for (int i = 0; i < num_cases; i++) {
int N = is.get_N();
std::vector<int> v = is.get_ints(N);
bool in_range = false;
int range_start;
for( int j = 0; j< N; j++ ) {
if (in_range) {
if (j == (N - 1)) {
print_range(range_start, v[j], false);
}
else if (in_range_cur(v, j)) {
continue;
}
else {
print_range(range_start, v[j], true);
in_range = false;
}
}
else {
if (j == (N - 1)) {
print_single(v[j], false);
}
else if (start_range_cur(v, j, N)) {
in_range = true;
range_start = v[j];
}
else {
print_single(v[j], true);
}
}
}
std::cout << '\n';
}
return 0;
}
I have a recursive void method which is written in c++. How can I exit from this recursive method when I get my needed value.
#include<bits/stdc++.h>
using namespace std;
int a[25];
char x[25];
int n, m ;
string s;
void go(int pos)
{
if(pos == n - 1)
{
int suma = a[0];
for(int i = 0 ; i < n - 1;i++)
{
if(x[i] == '+')suma += a[i + 1];
else suma -= a[i + 1];
}
//here I need hint how to close this method when suma will equal to m
//if(suma == x) here I should break this method
return ;
}
x[pos] = '+';
go(pos+1);
x[pos] = '-';
go(pos+1);
}
main()
{
cin >> n >> m;
for(int i = 0 ; i < n;i++)
cin >> a[i];
go(0);
for(int i = 0 ; i < n- 1;i++)
cout << x[i]<<" ";
}
I need to hint how to break void method when my summa will equal to x data everything was declared please do you know some hint for closing this method and I should get value of x arrays.
Throw where you have found your result, and catch at the initial call site
#include <string>
#include <iostream>
int a[25];
char x[25];
int n, m ;
std::string s;
struct result_found{};
void go(int pos)
{
if(pos == n - 1)
{
int suma = a[0];
for(int i = 0; i < n - 1; i++)
{
if(x[i] == '+')suma += a[i + 1];
else suma -= a[i + 1];
}
if (suma == m)
throw result_found{};
}
x[pos] = '+';
go(pos+1);
x[pos] = '-';
go(pos+1);
}
main()
{
std::cin >> n >> m;
for(int i = 0 ; i < n;i++)
std::cin >> a[i];
try {
go(0);
}
catch (result_found&) {}
for(int i = 0 ; i < n- 1;i++)
std::cout << x[i] << " ";
}
You may use an 'static bool' flag on the method.
static fields on functions keep their value between several functions calls.
void go(int pos)
{
static bool found=false;
if (found) return;
//rest of your code here...
//of course when you found what are you searching, do found = true;
}
For this program I have to fill an array with 20 random numbers (1-100), sort the array (descending) and then search for a random key value and output the position of that value if it is in the array. I am having 2 problems. First the while loop I have to exit the program is not working and I can not figure out why. Second my binary search is not returning a position value and I don't know why. This code will compile.
#include <iostream>
#include <ctime>
using namespace std;
int printArray(int *arr, int arraySize);
int fillArrayWithRandomNumbers(int *arr, int arraySize);
int bubbleSortDesc(int *arr, int arraySize);
int binarySearch(int *arr, int arraySize, int key);
int main()
{
int const arraySize = 20;
int arr[arraySize];
cout << "CMPSC 201-Extra Credit\n" << "This program fills an array, and then searches for a random key value." << endl <<endl;
char stopTheProgram = 'n';
do {
int key, result;
cout << "Unordered array:" << endl;
fillArrayWithRandomNumbers(arr, arraySize);
printArray(arr, arraySize);
cout << endl << "Array after a bubble sort : " <<endl;
bubbleSortDesc(arr, arraySize);
printArray(arr, arraySize);
key = rand()%100;
cout << endl <<"Searching for " << key << endl;
result = binarySearch(arr, key, arraySize);
if (result == -1)
{
cout << "Key " << key << " not found in the array" << endl;
}
else
{
cout << "Key " << key << " found at position " << result << endl;
}
cout << "Stop the program? (y/n) ";
cin >> stopTheProgram;
cout << endl;
} while (!(stopTheProgram == 'Y' || stopTheProgram == 'y'));
return 0;
}
int fillArrayWithRandomNumbers(int *arr, int arraySize)
{
srand((unsigned)time(NULL));
for (int i = 0; i<arraySize; i++)
{
arr[i] = (rand() % 100) + 1;
}
return *arr;
}
int printArray(int *arr, int arraySize)
{
for (int i = 0; i<arraySize; i++)
{
cout << arr[i] << " ";
}
return *arr;
}
int bubbleSortDesc(int *arr, int arraySize){
int i, j;
int temp = 0;
for (i = 0; i < arraySize; i++)
{
for (j = 0; j < arraySize - 1; j++)
{
if (arr[j] < arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return *arr;
}
int binarySearch(int arr[], int key, int arraySize)
{
int i, j;
int temp = 0;
for (i = 0; i < arraySize; i++)
{
for (j = 0; j < arraySize - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
int position, lowerBound = 0;
position = (lowerBound + arraySize) / 2;
while ((arr[position] != key) && (lowerBound <= arraySize))
{
if (arr[position] > key)
{
arraySize = position - 1;
}
else
{
lowerBound = position + 1;
}
position = (lowerBound + arraySize) / 2;
}
if (lowerBound <= arraySize)
{
position = 19 - position;
return position;
}
else {
return -1;
}
}
Solved: I now have fixed my problems with my binary search, and exiting my while loop. I am going to leave this here just in case anyone has my prof after me. So just to recap, this program fills an array with 20 random numbers (ranging 1-100), sorts the array in descending order and then creates a random key value (between 1-100). It then bubble sorts the array so it is in ascending order, uses a binary search to find the key value in the array and finally output the position of that key value if it is in the array.
I can see two issues with your code. First, you are shadowing the stopTheProgram variable. You define it once just before the do/while loop and initialize it to 'n'; Then once inside the do/while you define another stopTheProgram. This is a problem because of scoping. Inside the do/while loop the input from the user is assigned to the local stopTheProgram (defined in the do/while) but that ceases to exits outside the loop. So the while loop expression is always evaluated using the globally scoped stopTheProgram, which is set to 'n'. So remove the second definition. Second is an issue with the expression that controls the while loop. It always evaluates true. Draw a truth table if you can't visualize it. If stopTheProgram = 'Y' then the stopTheProgram != "Y" || stopTheProgram != 'y' is 0 || 1 which is always true. If stopTheProgram = 'y' then stopTheProgram != "Y" || stopTheProgram != 'y' is 1 || 0 which is always true. This works: while(!(stopTheProgram == 'Y' || stopTheProgram == 'y'))
I have this function called WordSort(worddata W [], int count) that is fed two variables
1 - worddata is the array holding information on a given word in a file. count is just the counter variable to see which word in the array we are looking at.
the words.txt file that is read into this program would just be a string of words.
this is a list of words
there are letters and numbers
23 people recommend this program.
Heres the function:
void WordSort (worddata W [], int count)
{
for (int i=1; i < count; i++)
{
for (int j=i; j > 0 && W[j-1].word > W[j].word; j--)
{
Swap(W[j], W[j-1]);
}
}
}
The swap function is suppose to swap every element with the one before it as long as j > 0 or the list is over. Im confused on how to complete the swap function, here's the example i was given.
void Swap (worddata & a, worddata & b)
{
int += a;
a = b;
b =+;
}
Swap is suppose to swap every element with the one before it
I think the WordSort function works fine, the only thing missing is the Swap function. Could anyone point me in the right direction or explain insertion sorting better to me?
void insertion_sort()
{
/* Algorithm : Insertion Sort
* Coded by .
*/
int num;
/*
* Asking the User no of Integers he/she wants to enter
*/
cout << "Enter no of integers u want to enter: ";
cin >> num;
/* Creating an Array to store the integers*/
int s[num];
/*Taking Integers from the User */
for(int i = 0 ; i < num ; i++)
{
cout << "Integer " << i+1 << " is : ";
int x;
cin >> x;
s[i] = x;
}
/* The Magic of INSERTION SORT */
for(int j = 1 ; j <= (num-1) ; j++)
{
int key = s[j];
int k = j-1;
while(k >=0 && key <= s[k])
{
s[k+1] = s[k];
k = k - 1;
}
s[k+1]=key;
}
/*Printing Out the Sorted List */
cout << "The Sorted List is \n\n";
for(int i = 0 ; i < num ; i++)
{
cout << s[i] << " ";
}
}
Use standard library std::swap instead. In your loop:
for (...)
{
std:swap(W[j], W[j-1]);
}
std::swap requires worddata class to have a copy constructor and an assignment operator defined explicitly or implicitly.
Swap should look like this -- I have no idea how your example is even close.
void Swap (worddata & a, worddata & b)
{
worddata temp = a;
a = b;
b = temp;
}
Insertion sort using "for loop" (2 iterations)
#include<iostream>
using namespace std;
int insertion(int arr[], int size_arr)
{
int i,j,n, temp;
for(i=1;i<size_arr; i++){
j=i-1;
temp = arr[i];
for (j; j >= 0; j--)
{
if(arr[j] > temp){
arr[j+1] = arr[j];
arr[j] = temp;
}
}
arr[j] = temp;
}
for(i=0;i<size_arr;i++){
cout<<arr[i]<<endl;
}
return 0;
}
int main(){
int arr[] = {3,38,1,44,66,23,105,90,4,6};
int size_arr = sizeof(arr) / sizeof(arr[0]);
insertion(arr,size_arr);
return 0;
}