I'm coding a recursive algorithm to take a user input N and make a N x N grid where the same number does not appear twice on either a row or a column. Almost everything's working, and duplicates don't appear in columns, but I'm having trouble getting rows working.
My code for checking duplicates in rows is the function noRowDuplicates. Duplicates are still appearing, and occasionally it'll throw a segmentation fault, but I'm not sure why.
Thanks in advance for the help!
// Author: Eric Benjamin
// This problem was solved using recursion. fill() is the recursive function.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void fillOptions();
void fill(int arrayPosition);
int inputNum;
int gridSize;
int *grid;
int allOptionsSize = 0;
int *allOptions;
int main() {
cout << "Please enter a number!" << endl;
cin >> inputNum;
gridSize = inputNum * inputNum;
grid = new int[gridSize];
allOptions = new int[inputNum];
for (int i = 0; i < inputNum; i++) {
allOptions[i] = i + 1;
allOptionsSize++;
}
srand((unsigned)time(0));
fill(0);
delete[] grid;
delete[] allOptions;
return 0;
}
bool noColumnDuplicates(int arrPosition, int valueToCheck) {
for (int i = 1; i < inputNum; i++) {
if (arrPosition - (inputNum * i) >= 0) {
if (grid[arrPosition - (inputNum * i)] == valueToCheck) {
return false;
}
}
}
return true;
}
bool noRowDuplicates(int arrPosition, int valueToCheck) {
int rowPosition = arrPosition % inputNum; // 0 to num - 1
if (rowPosition > 0) {
for (int p = 1; p < rowPosition; p++) {
if (grid[arrPosition - p] == valueToCheck) {
return false;
}
}
}
return true;
}
void fill(int arrayPosition) {
if (arrayPosition < gridSize) {
int randomPosition = rand() % allOptionsSize;
grid[arrayPosition] = allOptions[randomPosition];
if (noColumnDuplicates(arrayPosition, grid[arrayPosition])) {
if (noRowDuplicates(arrayPosition, grid[arrayPosition])) {
if (arrayPosition % inputNum == 0) {
cout << endl;
}
cout << grid[arrayPosition] << " ";
fill(arrayPosition + 1);
} else {
fill (arrayPosition);
}
} else {
fill(arrayPosition);
}
}
}
noRowDuplicates never tests the first element of a row, which makes sense when you are trying to fill the first element of a row, but not any other time.
Related
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
It is just a simple fibonacci array, but my code only gives stdout one time and it is two. FYI: this code may not be correct to compute the nth term of fibonacci array, but i am strugglling with this for loop.
I think the condition of i < n+1 is not meet, but why this for loop ends
nums[i] has size 2. You can't access nums[i] for i >= 2. An array doesn't grow. You can't change the size of an array. Use a std::vector. You've already included the header. A return statement finishes a function. In case of the main function it causes the program to stop. The return value of the main function by convention describes if the program was successful or errors occurred. You are returning
return nums[n];
That's probably not your intention. I assume you want to print the vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
std::vector<int> nums {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1) {
return 1;
} else {
nums.reserve(n + 1);
for (int i = 2; i < n + 1; i++)
{
cout << i << '\n';
nums.emplace_back(nums[i-2] + nums[i-1]);
}
for (const auto num : nums)
{
cout << num << '\n';
}
}
return 0;
}
it's because you can't access to nums[2] so the correct version of your code is :
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[5] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
you must provide estimated size to array or you will create vector or some dynamic array..
Your approach always give Segmentation fault;
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
vector<int> nums(n+1);
nums[0]=0;
nums[1]=1;
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
// cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
for(int i=0;i<n;i++)
{
cout<<nums[i]<<endl; }
}
return 0;
}
*/
a beginner at coding here.
I was practising loops(c++) when I stumbled upon this problem:-
Write a program in C++ to find the perfect numbers between 1 and 500. (6,28 and 496)
Perfect number: It is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
I wrote the following code:-
#include <iostream>
using namespace std;
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
}
return 0;
}
The code is supposed to print that 6, 28 and 496 are perfect numbers.
But instead, it's not printing anything. Haven't been able to find the error yet after checking for 30+ minutes.
Could anyone point out the error?
You forget to re-initialize some variables in your loop.
for seems more appropriate than while here.
Create sub function also help to "identify" scope.
#include <iostream>
bool isPerfectNumber(int n)
{
int sum = 0;
for (int div = 1; div != n; ++div) {
if (n % div == 0) {
sum += div;
}
}
return sum == n && n > 0;
}
int main()
{
for (int i = 2; i != 501; ++i) {
if (isPerfectNumber(i)) {
std::cout << n << " is a perfect number." << std::endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
bool perfect_num(int x);
int main() {
int m, n, x;
cout << "input the range m, n: " << "\n";
cin >> m >> n;
for (x = m; x <= n; ++x) {
if (perfect_num(x)) {
cout << x << " ";
}
}
return 0;
}
bool perfect_num(int x) {
bool flag = false;
//initialize
int sum = 0, i;
//loop 1 to x
for (i = 1; i < x; ++i) {
//judge whether is the factor
if (x % i == 0) {
sum += i;
}
}
//update flag
flag = (sum == x);
return flag;
}
#include<iostream>
using namespace std;
//judge function
bool isPerfectNum(int num){
int tmp = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
tmp += i;
}
}
return tmp == num;
}
int main(){
cout << "Perfect Number contains: ";
for (int i = 1; i <= 500; ++i){
if (isPerfectNum(i)) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
at the end of your first loop, you should bring back div and sum to their default value.
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
div = 1; // you should bring them back here.
sum = 0;
}
return 0;
}
So this program will print perfect numbers, but one of them, 2096128, is being printed for some reason? Would really appreciate some help figuring out what is happening! Thank you! I can't figure out why one non perfect number is finding it way into the sequence!
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
bool isPerfect(int n);
using namespace std;
int main() {
long long perfect = 0;
int first = 0;
first = (pow(2, 2 - 1))*(pow(2, 2) - 1);
cout << first << endl;
for (int i = 3, j = 1; j < 5; i += 2) {
if (isPerfect(i)) {
perfect = (pow(2, i - 1)*(pow(2, i) - 1));
cout << perfect << endl;
j++;
}
}
// pause and exit
getchar();
getchar();
return 0;
}
bool isPerfect(int n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else {
bool prime = true;
for (int i = 3; i < n; i += 2) {
if (n%i == 0) {
prime = false;
break;
}
}
return prime;
}
}
You're pretty much complicating this task.
Here's what I came up with:
#include <iostream>
using namespace std;
bool isPerfect(long long n);
int main()
{
int count = 5;
long long sum = 1;
for (int i = 3; count >= 0; i += 2)
{
sum += i * i * i;
if (isPerfect(sum))
{
cout << sum << endl;
count--;
}
}
system("pause");
return 0;
}
bool isPerfect(long long n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
sum += i;
}
return sum == n;
}
It sure isn't perfect, but will do for 5 numbers. Consider that it'll be very slow for more than 5 numbers.
I've been working on a program in one of my college classes. I have been having trouble with the implementation of my LRU code as it is not displaying any errors or anything, but compiles. There are two parts. The main that we input the values into, which we then specify which algorithm we want to use to find page faults. I know the main works, along with the FIFO algorithm, but I'm not getting anything with my LRU code (It compiles and "runs" but displays nothing as if I did not click to use the algorithm). Can anyone help me figure out what is wrong?
main.cpp
#include <iostream>
#include <string>
//#include "fifo.cpp"
#include "lru.cpp"
//#include "optimal.cpp"
using namespace std;
int main() {
// List of different variables
string pagestring;
int fs,pn[50], n;
// Prompt for page references
cout<<"Virtual Memory Simulation\nBy blah\n----------\nEnter the number of pages : " << endl;
cin >> n;
cout<<"\n-------------\nPlease enter a list of page numbers separated by commas.\n"<< endl;
cin>>pagestring;
// algorithm to use
char algo;
while (true) {
// Prompt algorithm to use
cout<<"----------\nPlease select an algorithm to use.\n\n1: First-In-First-Out (FIFO)\n2: Least-Recently-Used (LRU)\n3: Optimal\n0: Quit\n"<<endl;
cin>>algo;
if (algo == '1') {
//fifo(pagestring);
}
else if (algo == '2'){
LRU_Execute(pagestring, n);
}
else if (algo == '3'){
cout<<"Optimal Not yet coded"<<endl;
}
else if (algo == '0'){
break;
}
else {
cout<<"Invalid choice. Please try again."<<endl;
}
}
cout<<"Goodbye!!"<<endl;
};
LRU.cpp
#include <iostream>
#include <string>
using namespace std;
class pra
{
int fs,z;
int frame[50], frame1[50][2], pn[50], n, cnt, p, x;
public:
pra();
void init(string pagestring);
void getdata(string pagestring, int n);
void lru(int* pn, int n, string pagestring);
};
pra::pra()
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::init(string pagestring)
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::getdata(string pagestring, int n)
{
fs=3;
// index to loop through input string
int i = 0;
// current input string character
char z = pagestring[i];
int x = 0;
//cout << "\nEnter the page numbers : ";
while (z != '\0'){
// skip over commas and spaces
if (!(z == ',')) {
pn[x] = z;
x++;
// cout<<pn[x]<<"-This is pn[x]\n";
}
z = pagestring[++i];
}
//cout<<pn[x]<<"-This is pn[x] AGAIN\n";
this->lru(pn, n, pagestring);
}
void pra::lru(int* pn, int n, string pagestring)
{
init(pagestring);
int ind = 0, fault = 0, pi = 0, j, fn;
char i, z;
p = 0;
cnt = 0;
int min;
cout<<n<<"---"<<i<<" - "<<j<<" - "<<" - "<<fn<<" - "<<z;
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
pi = 0;
for (i = 0; i < n; i++)
{
j = 0;
if (ind > fs - 1)
ind = 0;
fault = 1;
min = 999;
while (j < fs)
{
if (frame1[j][0] = pn[pi])
{
fault = 0;
p++;
frame1[j][1] = p;
goto l2;
}
if (frame1[j][1] < min)
{
min = frame1[j][1];
fn = j;
}
j++;
}
j = 0;
while (j < fs)
{
if (frame1[j][0] = -1)
{
fault = 1;
fn = j;
goto l2;
}
j++;
}
ind++;
l2:
if (fault == 1)
{
p++;
frame1[fn][0] = pn[pi];
frame1[fn][1] = p;
cnt++;
}
cout << "\nElement: " << pn[pi];
pi++;
for (z = 0; z < fs; z++)
{
cout << "\t" << frame1[z][0];
}
if (fault == 1)
cout << "\t**Page Fault**";
else
cout << "\t--No Page Fault--";
}
cout << "\nTotal number of page faults: " << cnt;
cout << "\n";
}
void LRU_Execute(string pagestring, int n)
{
pra p;
int j, fault = 0, i, pi, z, fn, ind = 0, ans, ch;
p.getdata(pagestring, n);
//p.lru();
while (ans == 1);
//return 1;
}
I made a sudoku solver, but need to be able to take inputs in to set the puzzle before being solved. The input will be in a 1,2,,,,3,4 format where a space between 2 commas indicates a blank space (and obviously this will all be done row by row). I also have my code set up to use blank spots as 0s and would like to know how to read the input, parse each number into an int and also parse blanks as 0s.
As stated above, this is for C++ and is in Visual Studio Express 2013.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "cstdlib"
#include "stdio.h"
#include "iostream"
#include "sstream"
using namespace std;
//find the first empty slot on the puzzle
bool FindEmptyCell(int puzzle[9][9], int &row, int &colm);
//check if the inserted number is a legal move
bool isLegal(int puzzle[9][9], int row, int colm, int num);
//being solving through backtracking
bool solve(int puzzle[9][9])
{
int row, colm; //establish rows and columns
//check if there are any empty slots
if (!FindEmptyCell(puzzle, row, colm))
{
return true; //puzzle is assumed solved
}
else
{
//start backtracking with the number 1
for (int i = 1; i<10; i++)
{
if (isLegal(puzzle, row, colm, i))
{
puzzle[row][colm] = i;
if (solve(puzzle) == true)
{
return true; //if there is no problem with the first number, move on
}
else
{
puzzle[row][colm] = 0;
}
}
}
}
return false; //start recursion to try next number
}
//check if the move is legal in the 3x3 square, needs the row and column of the square
bool CheckSquare(int puzzle[9][9], int sqRow, int sqColm, int chkNum)
{
for (int row = 0; row < 3; row++)
{
for (int colm = 0; colm < 3; colm++)
{
if (puzzle[row + sqRow][colm + sqColm] == chkNum)
{
return true; //the number is there and the move is illegal
}
}
}
return false; //the number is not there and the move is assumed legal
}
//check if the move is legal in the row
bool CheckRow(int puzzle[9][9], int row, int chkNum)
{
for (int colm = 0; colm <9; colm++)
{
if (puzzle[row][colm] == chkNum)
{
return true; //the number is there and the move is illegal
}
}
return false; // the number is not there and the move is assumed legal
}
//check if the move is legal in the column
bool CheckColm(int puzzle[9][9], int colm, int chkNum)
{
for (int row = 0; row <9; row++)
{
if (puzzle[row][colm] == chkNum)
{
return true; //the number is there and the move is illegal
}
}
return false; // the number is not there and the move is assumed legal
}
//definition of finding empty slot method
bool FindEmptyCell(int puzzle[9][9], int &row, int &colm)
{
for (colm = 0; colm < 9; colm++)
{
for (row = 0; row < 9; row++)
{
if (puzzle[row][colm] == 0)
{
return true;
}
}
}
return false;
}
//definition of is legal method
bool isLegal(int p[9][9], int r, int c, int cN)
{
if (CheckRow(p, r, cN) == false)
{
if (CheckColm(p, c, cN) == false)
{
if (CheckSquare(p, r - r % 3, c - c % 3, cN) == false) //use % to find the beginning row/column of the square
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
int main()
{
int puzzle[9][9];
string input;
for (int i=1; i <10; i++)
{
for (int j=1;j <10; j++)
{
cout << "Please insert the number for ["<< i << "," << j << "] (0 for no number)" << endl;
getline(cin, input);
int value = atoi(input.c_str());
puzzle[i-1][j-1] = value;
//get puzzle into correct format
}
}
if (solve(puzzle) == true)
{
string s;
cout << "Solving the puzzle..." << endl;
//print the puzzle to the screen
for (int i = 0; i<9;i++)
{
for (int j = 0; j<9; j++)
{
cout << puzzle[i][j] << ",";
}
cout << endl;
}
cout << "Press any button to escape";
getline(cin, s);
}
else
{
cout << "Can not solve the puzzle" << endl;
}
return 0;
}
Not sure why you need the code but here it is. Everything works properly, it just doesnt take input in the correct format currently.
As your numbers are only of 1 digit, you can:
int puzzle[9][9] = {};
for (int i = 1; i < 10; ++i)
{
cout << "Please input row #" << i << ": ";
getline(cin, input);
int j = 0;
const char *ptr = input.c_str();
while (*ptr)
{
if (isspace(*ptr)) ; // do nothing
else if (*ptr == ',') ++j; // new column
else puzzle[i - 1][j] = *ptr - '0';
++ptr;
}
}
To parse empty spaces as zerors, you need:
Initialize your matrix to zeros int puzzle[9][9] = { };
read the input line by line (each line representing a whole row)
use function strtok() to split (separate) the values using delimeter `','
for each separated value, trim it (i.e. remove spaces). Then, Use function atoi to covert it as an integer
Notice that you should check for empty separated string if (strlen(str))