Flowchart for function overloding - algorithm

How we can draw flowchart and algorithm for function overloading
#include<iostream>
using namespace std;
int area(int);
int area(int,int);
float area(float);
float area(float,float);
Main function here
int main()
{
int s,l,b;
float r,bs,ht;
cout<<"Enter side of a
square:";
cin>>s;
cout<<"Enter length and
breadth of rectangle:";
cin>>l>>b;
cout<<"Enter radius of
circle:";
cin>>r;
cout<<"Enter base and height of triangle:";
cin>>bs>>ht;
cout<<"Area of square is"<<area(s);
cout<<"\nArea of rectangle is "<<area(l,b);
cout<<"\nArea of circle is "<<area(r);
cout<<"\nArea of triangle is "<<area(bs,ht);
}
For square
int area(int s)
{
return(s*s);
}
For rectangle
int area(int l,int b)
{
return(l*b);
}
For circle
float area(float r)
{
return(3.14*r*r);
}
For trianle
float area(float bs,float
ht)
{
return((bs*ht)/2);
}
It is possible to draw flowchart and algorithm for this program

Related

Whats wrong with my top down knapsack dp approach?

I am not able to figure out what is wrong with my top down knapsack dp approach, its failing testcases on below link, need help.
Question link: https://www.interviewbit.com/problems/0-1-knapsack/
Here is my code:
int fin(int i,int wt,int curprofit,vector<int>&A,vector<int>&B,int C,int n,vector<vector<int>>&dp)
{
if(i==n)
return curprofit;
if(dp[i][wt]!=-1)
return dp[i][wt];
int ret=0;
ret=max(ret,fin(i+1,wt,curprofit,A,B,C,n,dp));
if(wt+B[i]<=C)
{
ret=max(ret,fin(i+1,wt+B[i],curprofit+A[i],A,B,C,n,dp));
}
return dp[i][wt]= ret;
}
int Solution::solve(vector<int> &A, vector<int> &B, int C) {
int n=A.size();
vector<vector<int>>dp(n+1,vector<int>(C+1,-1));
return fin(0,0,0,A,B,C,n,dp);
}
Here's the fix, but I'd suggest you brush up on your recursion knowledge.
Calculate the max profit on the fly, not passing as the parameter. Otherwise, you'll need to put curprofit also in the dp state which will be costly. You may also see the output by removing the dp[][] caching. Just put up a correct recursive solution & memoize it.
int fin(int i,int wt,vector<int>&A,vector<int>&B,int C,int n,vector<vector<int>>&dp)
{
if(i==n)
return 0;
if(dp[i][wt]!=-1)
return dp[i][wt];
int ret=0;
ret=max(ret,fin(i+1,wt,A,B,C,n,dp));
if(wt+B[i]<=C)
{
ret=max(ret,fin(i+1,wt+B[i],A,B,C,n,dp) + A[i]);
}
return dp[i][wt]= ret;
}
int Solution::solve(vector<int> &A, vector<int> &B, int C) {
int n=A.size();
vector<vector<int>>dp(n+1,vector<int>(C+1,-1));
return fin(0,0,A,B,C,n,dp);
}

Knight's tour Problem - storing the valid moves then iterating

I tried to code the knight's tour problem(8X8 board), but somehow I am not able to get it to work.
Instead of exploring all possible knight moves, I am storing it and iterating it one by one but
the program gets terminated before printing the result.
tagged the buggy code and (shamelessly copied) working code in comments.
Thanks in advance :)
*if the board is traversed, print answer and return
* find all possible moves from given position
* for everyPosition in possiblePosition
* place the knight at everyPosition
* call the same function for the new position
* remove the knight from that position
import java.util.*;
import java.util.Map.Entry;
class Solution {
static int [][] res;
static int N;
static int row[];
static int col[];
public static void init(int n) { //initialize the array
res=new int[n][n];//n or N is the size of board which is 8
N=n;
for(int i=0;i<res.length;i++) {
for(int j=0;j<res[0].length;j++) {
res[i][j]=-1;
}
}
}
public static void print(int[][] res) { //helper function to print the 2d array
for(int i=0;i<res.length;i++) {
for(int j=0;j<res[0].length;j++) {
System.out.print(res[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
static boolean isValid(int r,int c){//check if the knight's move is inside the board then return true(<8 && >0)
return (r>=0 && c>=0 && r<N && c<N && res[r][c] == -1);
}
public static boolean solve(int a,int b,int sizeOfBoard,int count,int row[],int col[]) {
if(count==64)//if the board is traversed
{
System.out.println(":)");
print(res);
return true;
}
//**buggy code start**
ArrayList<ArrayList<Integer>>possibleKnightMoves=possibleKnightMoves(a,b,sizeOfBoard);
for(int i=0;i<possibleKnightMoves.size();i++) {//iterate over every possible knight move and check if the knight can be placed there or not
possibleKnightMoves=possibleKnightMoves(a,b,sizeOfBoard);
int x= possibleKnightMoves.get(i).get(0);
int y= possibleKnightMoves.get(i).get(1);
if(isValid(x,y)) {
res[x][y]=count;
if(solve(x,y,sizeOfBoard,count+1,row,col)) {
return true;
}else
{res[x][y]=-1;
}
}
}
//**buggy code end**
//**perfect working code, uncomment me and comment the buggy code(only for reference)**
// for(int i=0;i<N;i++) {
// int x=a+row[i];
// int y=b+col[i];
// if(isValid(x,y)) {
// res[x][y]=count;
// if(solve(x,y,sizeOfBoard,count+1,row,col))
// return true;//knight can be placed
// else
// res[x][y]=-1;
//
// }
//
// }
//**perfect working code end**
return false;//knight cant be placed at the square
}
public static ArrayList<ArrayList<Integer>> possibleKnightMoves(int a,int b,int sizeOfBoard) {
int x=a;
int y=b;
ArrayList<ArrayList<Integer>> result= new ArrayList<ArrayList<Integer>>();
for(int i=0;i<N;i++) {
x=x+row[i];// x,y represent all the possible knight moves from knight's current position
y=y+col[i];
result.add(new ArrayList<Integer>(Arrays.asList(x,y)));//add the moves to all possible moves list
}
return result;
}
public static void knightTour(int n) {
init(n);
res[0][0]=0;//set starting position
int array[]={2, 1, -1, -2, -2, -1, 1, 2 };//array 1 and array 2 represent the set of knight moves from (x,y) eg: x+2,y+1
row=array;
int array2[]={1, 2, 2, 1, -1, -2, -2, -1 };
col=array2;
solve(0,0,n,1,array,array2);//starting from 0,0 with count =1 as knight is already paced on 0,0
}
public static void main(String args[]) {
N=8;
knightTour(8);
init(8);
res[3][3]=1;
}
}
The problem is possibleKnightMoves method, where you wrote
for(int i=0;i<N;i++) {
x=x+row[i];current position
y=y+col[i];
result.add(new ArrayList<Integer>(Arrays.asList(x,y)));
}
Should be
for(int i=0;i<N;i++) {
x=a+row[i];//Changed here
y=b+col[i];//and here
result.add(new ArrayList<Integer>(Arrays.asList(x,y)));
}
Or else, the value of x and y adds on.
It is right now, but there is still one problem: your code runs too slow.
Consider this line
ArrayList<ArrayList<Integer>>possibleKnightMoves=possibleKnightMoves(a,b,sizeOfBoard);
And this line in the for loop:
possibleKnightMoves=possibleKnightMoves(a,b,sizeOfBoard);
You repeated doing the same thing several times, which if you just remove the line in the for loop, the result won't change but runs faster. So I think this is what you want:
import java.util.*;
import java.util.Map.Entry;
public class Main {
static int [][] res;
static int N;
static int row[];
static int col[];
public static void init(int n) { //initialize the array
res=new int[n][n];//n or N is the size of board which is 8
N=n;
for(int i=0;i<res.length;i++) {
for(int j=0;j<res[0].length;j++) {
res[i][j]=-1;
}
}
}
public static void print(int[][] res) { //helper function to print the 2d array
for(int i=0;i<res.length;i++) {
for(int j=0;j<res[0].length;j++) {
if(res[i][j] == -1) {
System.out.print("n ");
}else {
System.out.print(res[i][j]+" ");
}
}
System.out.println();
}
System.out.println();
}
static boolean isValid(int r,int c){//check if the knight's move is inside the board then return true(<8 && >0)
return (r>=0 && c>=0 && r<N && c<N && res[r][c] == -1);
}
public static boolean solve(int a,int b,int sizeOfBoard,int count,int row[],int col[]) {
if(count==64){
System.out.println(":)");
print(res);
return true;
}
ArrayList<ArrayList<Integer>>possibleKnightMoves=possibleKnightMoves(a,b,sizeOfBoard);
for(int i=0;i<possibleKnightMoves.size();i++) {//iterate over every possible knight move and check if the knight can be placed there or not
int x= possibleKnightMoves.get(i).get(0);
int y= possibleKnightMoves.get(i).get(1);
if(isValid(x,y)) {
res[x][y]=count;
if(solve(x,y,sizeOfBoard,count+1,row,col)) {
return true;
}else{
res[x][y]=-1;
}
}
}
return false;//knight cant be placed at the square
}
public static ArrayList<ArrayList<Integer>> possibleKnightMoves(int a,int b,int sizeOfBoard) {
ArrayList<ArrayList<Integer>> result= new ArrayList<ArrayList<Integer>>();
for(int i=0;i<N;i++) {
int x=a+row[i];//Changed here
int y=b+col[i];//and here
result.add(new ArrayList<Integer>(Arrays.asList(x,y)));
}
return result;
}
public static void knightTour(int n) {
init(n);
res[0][0]=0;//set starting position
int array[]={2, 1, -1, -2, -2, -1, 1, 2 };//array 1 and array 2 represent the set of knight moves from (x,y) eg: x+2,y+1
row=array;
int array2[]={1, 2, 2, 1, -1, -2, -2, -1 };
col=array2;
solve(0,0,n,1,array,array2);//starting from 0,0 with count =1 as knight is already paced on 0,0
}
public static void main(String args[]) {
N=8;
knightTour(8);
init(8);
res[3][3]=1;
}
}

Facing error in running the programming

I am trying to run this program, taking vertices of a triangle as inputs.
But i am facing errors. Can someone help me with this ?
What I am trying to do create a point class, inherit in a triangle class and accept the vertices of triangle as inputs.
#include <iostream>
#include <vector>
using namespace std;
#Defines a class Point.
class Point
{
private:
float x;
float y;
public:
int read_Point(Point &P)
{
std::cin >> P.x >> P.y;
}
};
#Defines a class Triangle
class Triangle : public Point
{
private:
std::vector<Point> P;
public:
int make_triangle()
{
P=std::vector<Point>(3);
read_Traingle();
return 0;
}
void read_Traingle()
{
read_Point(P[1]);
read_Point(P[2]);
read_Point(P[3]);
}
};
int main()
{
Triangle Tri;
Tri.make_triangle();
return 0;
}
You initialized the vector with 3 P=std::vector<Point>(3); then you tried to read the element P[3] read_Point(P[3]);
increase the size of vector or read the vector starting with index zero.

N-dimensional tensor based on std::vector

I want to define n-dimensional data structure using std::vector. I have a problem with definition of operator(). Lets have a look at a sample 2D structure
class my_data {
public:
my_data (size_t N, size_t M) : tab(N*M), _N(N), _M(M) {}
const double& operator() (size_t i, size_t j) const {
return tab.at(i * M + j);
}
double& operator() (size_t i, size_t j) {
return tab.at(i * M + j);
}
private:
std::vector<double> tab;
size_t _N;
size_t _M;
};
I would like to define such a structures for any dimension using templates , but I don't know if it is possible. So basically what I would like to have is something like that
my_data<4> vec (1,2,3,4);
defines 4D 'tensor' with sizes 1,2,3,4 (number of all elements 1*2*3*4). You can now access and change values by typing
vec (0,0,0,0) = 2.0;
The below solution uses some of the C++14 and C++1z features, but they can be easily ported to C++11:
#include <vector>
#include <utility>
#include <array>
#include <cstddef>
namespace detail
{
template <typename T, typename S>
class my_data;
template <typename T, std::size_t... Is>
class my_data<T, std::index_sequence<Is...>>
{
public:
my_data(decltype(Is)... size)
: t((size * ...)), s{{ size... }}
{}
T& operator()(decltype(Is)... i)
{
return t.at(index({{ i... }}));
}
const T& operator()(decltype(Is)... i) const
{
return t.at(index({{ i... }}));
}
private:
std::size_t index(const std::array<std::size_t, sizeof...(Is)>& a) const
{
std::size_t ind = a[0];
for (std::size_t i = 1; i < a.size(); ++i)
{
ind = ind * s[i] + a[i];
}
return ind;
}
std::vector<T> t;
const std::array<std::size_t, sizeof...(Is)> s;
};
}
template <typename T, std::size_t N>
using my_data = detail::my_data<T, std::make_index_sequence<N>>;
Test:
int main()
{
my_data<double, 4> vec(1,2,3,4);
vec(0,0,0,0) = 2.0;
}
DEMO
DEMO (C++11)

Run time error in graph

I am implementing Graph for the first time and for that I took this problem from SPOJ.
Took help of geeksforgeeks, applied union find algorithm to find out whether or not graph contains a cycle but I get run time error (SIGSEGV).
Can you please help why is it so?
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
struct Edge{
int s,d;
};
struct Graph{
int v,e;
struct Edge* edge;
};
struct Graph* create(int v, int e){
struct Graph* graph=(struct Graph*)malloc(sizeof (struct Graph));
graph->v=v;
graph->e=e;
graph->edge=(struct Edge*)malloc(sizeof (struct Edge));
return graph;
};
int Find(int p[],int i)
{
if (p[i] == -1)
return i;
return Find(p, p[i]);
}
void Union(int p[],int i, int j)
{
p[j]=i;
}
bool CheckCycle(struct Graph* graph)
{
int *p=(int*)malloc(graph->v* sizeof (int));
memset(p,-1,graph->v * sizeof (int));
/*for(int i=0;i<graph->v;i++)
cout<<"p"<<i<<"="<<p[i];
cout<<"\n";*/
for(int i=0;i<graph->e;i++)
{
/*cout<<"edge"<<i<<" src="<<graph->edge[i].s<<"\n";
cout<<"edge"<<i<<" dest="<<graph->edge[i].d<<"\n";*/
int x=Find(p,graph->edge[i].s);
int y=Find(p,graph->edge[i].d);
/*cout<<"x="<<x<<" "<<"y="<<y<<"\n";*/
if(x==y)
return true;
Union(p,x,y);
}
return false;
}
int main()
{
ios_base::sync_with_stdio(false);
int N,M,v1,v2;
cin>>N>>M;
if(M!=(N-1))
cout<<"NO\n";
else{
struct Graph* graph=create(N,M);
for(int i=0;i<M;i++)
{
cin>>v1;
graph->edge[i].s=v1-1;
cin>>v2;
graph->edge[i].d=v2-1;
}
if(CheckCycle(graph))
cout<<"NO\n";
else
cout<<"YES\n";
}
}
One issue is this in your main program:
graph->edge[i].s=v1-1;
You created a single edge. If i is greater than 0, then this is an out-of-bounds access.
Look how you created edge in the create function:
graph->edge=(struct Edge*)malloc(sizeof (struct Edge));
That allocation holds a single edge, not multiple edges. Given how you coded the rest of your program in a C-like fashion, what you probably wanted is this:
graph->edge=(struct Edge*)malloc(sizeof(Edge) * e);
Also, you should strive to not use single-letter variable names. It is hard to read code with e, v, etc. as member variable names. Name those items m_edge, m_vertex or something that is more descriptive.

Resources