Bubble Sort Ragged Table in C - bubble-sort

I was trying to sort a ragged table using bubble sort. The algorithm I have only sorts the first row, but leaves the rest of the rows unsorted. I think the problem is the fact that the "last" variable is not properly initialized.
void bubbleSort (int **table)
{
// Local Declarations
int temp;
int current;
int walker;
int column;
int row=0;
int numCol = 0;
int last = *table[numCol];
// Statements
while (table[row] != NULL) {
for (column = 2; column <= *table[row]; column++) {
for (current = 2; current < last; current++) {
bool swapsOccured = false;
for (walker = last; walker > current; walker--) {
if (table[row][walker] > table[row][walker - 1]) {
swapsOccured = true;
temp = table[row][walker];
table[row][walker] = table[row][walker - 1];
table[row][walker - 1] = temp;
} // if
} // for walker
if (!swapsOccured)
return;
} // for current
}
row++;
} // while
return;
}

Related

My word search II solution is very slow (Leetcode 212)

My solution is correct and passes all test cases, but my solution is very slow (faster than 7% of C++ solutions).
Question:
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
By the way, I don't have Leetcode premium and looked at the discussion. I see that other people are using recursion. I am using a stack, but this shouldn't really be a problem. Does anyone see any performance issues with my code? The complexity should be O(n^2*3^n)
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> ret;
Trie* root = new Trie();
for (const auto &i:words) {
root->insert(i);
}
Trie* cnode = root;
int numRow = board.size();
int numCol = board[0].size();
vector<int> temp(numCol, 0);
vector<vector<int>> visited(numRow, temp);
for (int i = 0; i < numRow; ++i) {
for (int j = 0; j < numCol; ++j) {
stack<pair<int, int>> searcher;
searcher.push(make_pair(i,j));
while (!searcher.empty()) {
int row = searcher.top().first;
int col = searcher.top().second;
int cur = board[row][col] - 97;
if (visited[row][col]) {
cnode = cnode->parent;
visited[row][col] = 0;
searcher.pop();
} else if (cnode->child[cur] == nullptr) {
searcher.pop();
visited[row][col] = 0;
} else {
visited[row][col] = 1;
cnode = cnode->child[cur];
if (cnode->contain != "") {
ret.push_back(cnode->contain);
cnode->contain = "";
}
if (row + 1 < numRow && !visited[row + 1][col]) {
searcher.push(make_pair(row+1, col));
}
if (row - 1 >= 0 && !visited[row-1][col]) {
searcher.push(make_pair(row-1, col));
}
if (col + 1 < numCol && !visited[row][col+1]) {
searcher.push(make_pair(row, col+1));
}
if (col - 1 >= 0 && !visited[row][col-1]) {
searcher.push(make_pair(row, col-1));
}
}
}
}
}
return ret;
}
class Trie {
public:
vector<Trie*> child;
Trie* parent;
string contain;
Trie() {
child = vector<Trie*>(26, nullptr);
contain = "";
parent = nullptr;
}
void insert(string word) {
Trie* root = this;
for (int i = 0; i < word.size(); ++i) {
int loc = word[i] - 97;
if (root->child[loc] == nullptr) {
root->child[loc] = new Trie();
root->child[loc]->parent = root;
}
root = root->child[loc];
}
root->contain = word;
}
};
};

Josephus Election Problem array implementation

I am trying to implement the Josephus election problem using an array as a mock circular linkedlist.
The item and next arrays represent nodes for circular linked list. On every Mth element one element is marked for removal. The next array skips over the marked index.
When there is one element left in the array we print out the element and the item that is left.
The problem is from Sedgewick C++ Algorithms books Chapter Third Edition. exercise 3.31.
The output I am getting is incorrect, I am not lost.
void array_represent_linked_list(int num_ints, int M) {
int* item = new int[num_ints];
int* next = new int[num_ints];
//populated item and next array with elements
for (int index = 0; index < num_ints; index++) {
item[index] = index + 1;
if (index == (num_ints - 1)) {
next[index] = 0;
}
else {
next[index] = index + 1;
}
}
int nums_left = num_ints;
int x = 0;
int count = 0;
int last_element_index = 0;
while ( nums_left > 1) {
//if current value divisible by M-2?
if ((count % M-2) == 0) {
if ((nums_left - 1) == 1) {
//record the next index which is the last element
last_element_index = next[x];
}
else {
//mark for removal of element from array
next[x] = next[next[x]];
}
nums_left -= 1;
}
//move to next element of array
x = next[x];
count++;
}
std::cout << item[last_element_index]<< " " << last_element_index<< std::endl;
}
output for
array_represent_linked_list(9,5); //item[x] =8 , next[x] = 7
After writing a brute force method which looks at each individual element in the item array and setting each element to 0 when we reach a skip factor of M. I was able to test with this code snippet and get the correct answers.
Breaking down the problem, every M-1 elements should set the next[index] to next[next[index]] , and we traverse the array with x = next[x].
void array_represent_linked_list(int num_ints, int M) {
int* item = new int[num_ints];
int* next = new int[num_ints];
//populated item and next array with elements
for (int index = 0; index < num_ints; index++) {
item[index] = index + 1;
if (index == (num_ints - 1)) {
next[index] = 0;
}
else {
next[index] = index + 1;
}
}
int nums_left = num_ints;
//used to track elements in item array
int index = 0;
//used to count number of elemenets traversed in the list
int count = 0;
//store the return values
int return_index = 0;
int return_val = 0;
while (nums_left > 1) {
count += 1;
if (count == (M - 1)) {
//reset the count after reaching 4 elements
count = 0;
//update next element
next[index] = next[next[index]];
//decrease nums found
nums_left -= 1;
}
//traverse to next element
index = next[index];
}
return_index = index;
return_val = item[next[index]];
std::cout << return_index << " " << return_val << std::endl;
}
The book gives a linked list implementation similar to the following:
struct node {
int item;
node* next;
node(int x, node* t) {
item = x;
next = t;
}
};
typedef node *link;
int josephusLinkedList(int n, int k) {
link t = new node(1, 0);
t->next = t;
link x = t;
for (int i = 2; i <= n; i++) {
x = (x->next = new node(i, t));
}
while (x != x->next) {
for (int i = 1; i < k; i++) x = x->next;
x->next = x->next->next;
}
return x->item;
}
We can write a very similar implementation that simulates the linked list using an array next where the index of the array represents the node and the value represents the pointer to the next node.
int josephusArray(int n, int k) {
int *next = new int[n];
for (int i = 0; i < n; i++) {
next[i] = (i + 1) % n;
}
int x = 0;
while (x != next[x]) {
for (int j = 1; j < k; j++) x = next[x];
next[x] = next[next[x]];
}
return x;
}
We initialize the next array by setting each value to the next index, until we reach the end, which we set to 0, the first index. This simulates the circular linked list that is the starting condition of the problem.
The while loop then eliminates every kth element by advancing through the next array k-1 times, then "removing" the next element by setting next[x] = next[next[x]];, which is very similar to how we remove an element from a linked list. (The element isn't really removed from the array, but it will be skipped in future traversals because no value will point to that element.)

Unable to set breakpoints to see errors C++ ORDERED LIST

I am having a problem trying to use breakpoints in my code to see what is happening step by step. No matter where I put one in my code, it says it can't reach it (even though the code is running through all the functions I told it to), even if I set a conditional to true that definitely should be true (count == 3 for example).
I am setting up an ordered list that inserts movies as strings with certain details for a college project, it adds the movies in order, and then you should be able to delete a specific title. I have used an ordered list using numbers i got working to set this one up as to why I am getting errors, but I cant see what happening as it wont reach any breakpoints, even if i put one on the constructor before anything else is ran. Can anyone tell me why this is happening or what might be wrong with my code. My list remove() function is just removing the last element, instead of the one I have defined.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class OList
{
private:
string data[3];
int count; //First empty slot
public:
OList();
bool isEmpty();
bool isFull();
void Add(string newVal);
string Remove(string newVal);
bool LinearSearch(string searchVal);
void Display();
};
OList::OList()
{
count = 0;
}
bool OList::isEmpty()
{
if (count == 0)
{
return true;
}
else
{
return false;
}
}
bool OList::isFull()
{
if (count == 5)
{
return true;
}
else
{
return false;
}
}
void OList::Add(string movie)
{
data[count] = movie;
int i;
if (isFull())
return;
//Find the insertion point
for (i = 0; i < count; i++);
if (i == count)
data[i] = movie; //Copy in the new value
else
//Make a Space
for (int j = count - 1; j >= i; j--)
{
data[j + 1] = data[j];
}
data[i] = movie; //Copy in the new value
count++;
}
string OList::Remove(string movie)
{
int i = LinearSearch(movie);
string temp = movie;
if (isEmpty())
return false;
i++;
while (i < count - 1)
{
data[i] = data[i + 1];
i++;
}
count--;
return temp;
}
bool OList::LinearSearch(string searchVal)
{
for (int i = 0; (i < count) || (data[i] > searchVal); i++)
{
if (data[i] == searchVal)
return -1;
}
return false;
}
void OList::Display()
{
for (int i = 0; i < count; i++)
{
cout << data[i] << endl;
}
}
int main()
{
OList movies;
string movie;
movies.Add(movie = "Yeh Jawaani Hai Deewani | 1, 790, 000, 000 | Ayan Mukerji");
movies.Add(movie = "Dhoom 3 | 2,840,000,000 | Vijay Krishna Acharya");
movies.Add(movie = "Chennai Express | 2, 275, 000, 000 | Rohit Shetty");
movies.Display();
std::cout << "\n";
movies.Remove(movie = "Chennai Express | 2, 275, 000, 000 | Rohit Shetty");
movies.Display();
system("pause");
return 0;
}
Just looking at your Add function here, not going to go through whole program. Lets say count is 0
void OList::Add(string movie)
{
data[count] = movie; //data[0] = movie;
int i;
if (isFull())
return;
//Find the insertion point
for (i = 0; i < count; i++); //i = 0
if (i == count) //if i == 0, which we know it does
data[i] = movie; //data[0] = movie; AGAIN
else //never enter this...
//Make space
for (int j = count - 1; j >= i; j--)//never get here
{
data[j + 1] = data[j];//nope
}
data[i] = movie; //data[0] = movie; just to be sure
count++;
}
It might as well be
void OList::Add(string movie)
{
data[count] = movie;
if (isFull())
return;
count++;
}

Huffman coding c++

So I am working on Huffman coding for a project. However, my code just doesn't work. When i ran it on visual studio, it didn't give me an error. What I was trying to do is to read a file and put all of them into a string. And get the frequency for each character in that string. But I think when the file got a little bit large, it seems like my code is running in a infinite loop. Can anyone explain anything to me? By the way, I had a sorted function that I used to sort a vector of node* by their frequency.
ifstream infile;
infile.open(filename);
string q;
string line;
while (getline(infile, line))
{
q += line;
}
char y;
int count = 0;
int check = 0;
for (int i = 0; i < q.size(); i++) //if the string gets big, it seems to become an infinite loop in here
{
y = q[i];
for (int x = i - 1; x > 0; x--) //make sure not counting the same char
{
if (y == q[x])
{
check++;
}
}
if (check == 0)
{
for (int i = 0; i < q.size(); i++)
{
if (q[i] == y)
{
count++;
}
}
node*x = new node;
x->char1 = y; //my node have char
x->freq = count; //my node has frequency
list1.push_back(x);
}
count = 0;
check = 0;
}
sort(list1.begin(), list1.end(), sorter); //sort them from small to big
while (list1.size() > 1)
{
node*left = list1[0];
node*right = list1[1];
list1.erase(list1.begin(), list1.begin() + 2);
double sum = left->freq + right->freq;
node* x = new node;
x->freq = sum;
x->left = left;
x->right = right;
list1.push_back(x);
sort(list1.begin(), list1.end(), sorter);
}
list1.clear();
return true;
The following is my sort function
static struct {
bool operator()(NodeInterface* a, NodeInterface* b) {
if (a->getFrequency() == b->getFrequency()) {//if the frequencies are even,
if (b->getCharacter() == '\0') return false;
if (a->getCharacter() != '\0') {
return (int)a->getCharacter() < (int)b->getCharacter();
}
return false;
}
return a->getFrequency() < b->getFrequency();
}
} sorter;
I see two major problems.
You have a for loop inside a for loop both initializing and using int i
Change the variable name of the inner loop.
for (int i = 0; i < q.size(); i++) //if the string gets big, it seems to become an infinite loop in here
.
.
if (check == 0)
{
for (int i = 0; i < q.size(); i++) //Change this to int j for example
{
.
.
And the Sorter struct. I would rewrite it as this.
static struct {
bool operator()(NodeInterface* a, NodeInterface* b) {
if (a->getFrequency() == b->getFrequency()) {//if the frequencies are even,
if (b->getCharacter() == '\0') return false;
if (a->getCharacter() == '\0') return true;
return (int)a->getCharacter() < (int)b->getCharacter();
}
return a->getFrequency() < b->getFrequency();
}
} sorter;
A few suggestions for your for loop:
for (int i = 0; i < q.size(); i++) //if the string gets big, it seems to become an infinite loop in here
{
y = q[i];
//You can avoid this entire loop by using a structure like map
for (int x = i - 1; x > 0; x--) //make sure not counting the same char
{
if (y == q[x])
{
check++;
//break; //if you use a loop, break it once you find the character.
}
}
if (check == 0)
{
for (int j = 0; j < q.size(); j++)//Renamed variable + you can start this loop from j = i as you know there is no occurrence of y before that.
{
if (q[i] == y)
{
count++;
}
}
node*x = new node;
x->char1 = y; //my node have char
x->freq = count; //my node has frequency
list1.push_back(x);
}
count = 0;
check = 0;
}

Using a insertion sort function for two dimensional array in C++?

One of the functions I am doing uses a insertion sort for a two dimensional array with 2 rows and 12 columns. The first row is for student IDs, so there are 12 students total. The second row has the corresponding GPA for each student. I am not sure how to come up with an insertion sort to sort the GPA numbers in ascending order. Any help would be awesome!
I have this so far.
void insertionSort(double avg[][COLS])
{
int current = 1;
int last = COLS - 1;
int temp;
int walker;
int row = 1;
while (current <= last)
{
temp = avg[row][current];
walker = current - 1;
while (walker >= 0
&& temp < avg[row][walker])
{
avg[row][walker+1] = avg[row][walker];
walker = walker - 1;
}
avg[row][walker+1] = temp;
current = current + 1;
}
Your problem is that temp variable is declared as an int it should be double also you should swap the ids too
void insertionSort(double avg[][COLS])
{
int current = 1;
int last = COLS - 1;
double temp;//this was an int
int walker;
int row = 1;
while (current <= last)
{
temp = avg[row][current];
walker = current - 1;
while (walker >= 0
&& temp < avg[row][walker])
{
avg[row][walker+1] = avg[row][walker];
avg[row-1][walker+1] = avg[row-1][walker];//swap the id of two students
walker = walker - 1;
}
avg[row][walker+1] = temp;
avg[row-1][walker+1] = temp;
current = current + 1;
}
}