Mql5 function for selecting open orders by Ticket, then Symbol, and trade Direction - algorithmic-trading

Total newbie to Mql5, and need some help with this int OpenOrders() piece of code originally from Mql4 EA's, that finds open positions - (if any), and selects originally by SYMBOL, and MAGIC Number, and the expert doesn't open any other positions for as long as a trade it has opened on that symbol has not yet been closed.
I wish the EA to identify a TICKET it has opened, related SYMBOL, and POSITION_TYPE to be used in the ONTICK, and not open any other trades on the same chart until that one position is closed, but can continue trading on any other charts.
input double LotSize =0.3;
input double Incriment =0.01;
input int StopLoss =50;
input int TakeProfit =100;
input int Trend =21;
input int Momentum =21;
input int Strength =13;
int adxlevel =34;
int buylevel =62;
int selllevel =36;
//---------------------
double pips;
#include <Trade\Trade.mqh>
CTrade Execute;
ulong passport, StopLevel;
double ask, bid;
double takeout=0,stopout=0;
int moving,rsi,adx,Spread;
//+------------------------------------------------------------------+
int OnInit()
{
//---
double ticksize = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
if(_Digits==3||_Digits==4)
pips=ticksize*1000;
else
pips =ticksize;
//---
moving=iMA(_Symbol,PERIOD_CURRENT,Trend,0,MODE_SMA,PRICE_CLOSE);
rsi=iRSI(_Symbol,PERIOD_CURRENT,Momentum,PRICE_MEDIAN);
adx=iADX(_Symbol,PERIOD_CURRENT,Strength);
//---
return(INIT_SUCCEEDED);
}
***int OpenOrders()
{
int BUYS=0,SELLS=0;
for(int i=0; i<PositionsTotal(); i++)
{
if(PositionSelectByTicket(passport)==false) break;
int dealtype=(int)PositionGetInteger(POSITION_TYPE); // buy or sell
// string position_symbol=PositionGetString(POSITION_SYMBOL); // chart symbol
if(Symbol()==PositionGetSymbol(i) && passport==PositionGetTicket(POSITION_TICKET))
{
if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) BUYS++;
if(PositionGetInteger(POSITION_TYPE)==ORDER_TYPE_SELL) SELLS++;
}
}
//---
if(BUYS>0) return(BUYS);
else return(SELLS);
}***
//+------------------------------------------------------------------+
void OnTick()
{
//---
MqlRates rates[3];
double movingarray[],rsiarray[],adxarray[];
CopyRates(_Symbol,PERIOD_CURRENT,1,3,rates);
CopyBuffer(rsi,0,1,3,rsiarray);
CopyBuffer(adx,0,1,3,adxarray);
ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
Spread=int(SymbolInfoInteger(_Symbol,SYMBOL_SPREAD));
StopLevel=SymbolInfoInteger(Symbol(),SYMBOL_TRADE_STOPS_LEVEL);
//---
if(OpenOrders()==0)
{
if(rates[0].open > moving )// CONDITION
if(rsiarray[0] > buylevel && rsiarray[1] < buylevel )//SIGNAL
{
if(TakeProfit>0) takeout=ask+TakeProfit*pips;
if(StopLoss>0) stopout=ask-StopLoss*pips;
Execute.Buy(LotSize,NULL,ask,stopout,takeout,NULL);
passport=Execute.ResultOrder();
Print("BUY Opened");
}
if(rates[0].open < moving )//CONTITION
if(rsiarray[0] < selllevel &&rsiarray[1] > selllevel )//SIGNAL
{
if(TakeProfit>0) takeout=bid+TakeProfit*pips;
if(StopLoss>0) stopout=bid-StopLoss*pips;
Execute.Sell(LotSize,NULL,bid,stopout,takeout,NULL);
passport=Execute.ResultOrder();
Print("SELL Opened");
}
}
//---
if(OpenOrders()>0)
{
int dealtype=(int)PositionGetInteger(POSITION_TYPE);
if(dealtype==POSITION_TYPE_BUY)
if(rsiarray[0] < buylevel )
{
Execute.PositionClose(passport);
passport=0;
}
else if(dealtype==POSITION_TYPE_SELL)
if(rsiarray[0] > selllevel )
{
Execute.PositionClose(passport);
passport=0;
}
}
}

I think what you really after is this:
input double LotSize =0.3;
input double Incriment =0.01;
input int StopLoss =50;
input int TakeProfit =100;
input int Trend =21;
input int Momentum =21;
input int Strength =13;
int adxlevel =34;
int buylevel =62;
int selllevel =36;
//---------------------
double pips;
#include <Trade\Trade.mqh>
CTrade Execute;
ulong StopLevel;
double ask, bid;
double takeout=0,stopout=0;
int moving,rsi,adx,Spread;
//+------------------------------------------------------------------+
int OnInit()
{
//---
double ticksize = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
if(_Digits==3||_Digits==4)
pips=ticksize*1000;
else
pips =ticksize;
//---
moving=iMA(_Symbol,PERIOD_CURRENT,Trend,0,MODE_SMA,PRICE_CLOSE);
rsi=iRSI(_Symbol,PERIOD_CURRENT,Momentum,PRICE_MEDIAN);
adx=iADX(_Symbol,PERIOD_CURRENT,Strength);
//---
Execute.SetExpertMagicNumber(0xCAFE); // INCLUDED
Execute.SetAsyncMode(false); // CHANGED
return(INIT_SUCCEEDED);
}
int OpenPositions(ulong &passport)
{
int BUYS=0,SELLS=0;
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket=PositionGetTicket(i); // changed
if(PositionSelectByTicket(ticket)==false) break;
int dealtype=(int)PositionGetInteger(POSITION_TYPE); // buy or sell
// string position_symbol=PositionGetString(POSITION_SYMBOL); // chart symbol
if(Symbol()==PositionGetSymbol(i) && 0xCAFE==PositionGetInteger(POSITION_MAGIC)) // CHANGED
{
passport = ticket; // CHANGED
if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) BUYS++;
if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL) SELLS++; // CHANGED
}
}
//---
if(BUYS>0) return(BUYS);
else return(SELLS);
}
//+------------------------------------------------------------------+
void OnTick()
{
//---
MqlRates rates[3];
double movingarray[],rsiarray[],adxarray[];
CopyRates(_Symbol,PERIOD_CURRENT,1,3,rates);
CopyBuffer(rsi,0,1,3,rsiarray);
CopyBuffer(adx,0,1,3,adxarray);
ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
Spread=int(SymbolInfoInteger(_Symbol,SYMBOL_SPREAD));
StopLevel=SymbolInfoInteger(Symbol(),SYMBOL_TRADE_STOPS_LEVEL);
//---
ulong passport = 0; // CHANGED
int positions = OpenPositions(passport); // CHANGED
if(positions==0) // CHANGED
{
if(rates[0].open > moving )// CONDITION
if(rsiarray[0] > buylevel && rsiarray[1] < buylevel )//SIGNAL
{
if(TakeProfit>0) takeout=ask+TakeProfit*pips;
if(StopLoss>0) stopout=ask-StopLoss*pips;
Execute.Buy(LotSize,NULL,ask,stopout,takeout,NULL);
Print("BUY Opened");
}
if(rates[0].open < moving )//CONTITION
if(rsiarray[0] < selllevel &&rsiarray[1] > selllevel )//SIGNAL
{
if(TakeProfit>0) takeout=bid+TakeProfit*pips;
if(StopLoss>0) stopout=bid-StopLoss*pips;
Execute.Sell(LotSize,NULL,bid,stopout,takeout,NULL);
passport=Execute.ResultDeal(); // CHANGED
Print("SELL Opened");
}
}
else if(positions>0) // CHANGED to prevent on the same tick do both
{
int dealtype=(int)PositionGetInteger(POSITION_TYPE);
if(dealtype==POSITION_TYPE_BUY)
if(rsiarray[0] < buylevel )
{
Execute.PositionClose(passport);
}
else if(dealtype==POSITION_TYPE_SELL)
if(rsiarray[0] > selllevel )
{
Execute.PositionClose(passport);
}
}
}
I dont tested the changes. And it should be fine most part of time. It will only have problems when having delay to execute the Buy/Sell stuff.

Related

distance between any two nodes in a graph(based on edges between them)

The below code in c++ is to find the distance between any two nodes in a graph but there is some logical error where I tried to find but can't. Everything seems to be perfect but I can say that there is something wrong with a break inside if condition inside for loop which is inside while(s.!empty()).
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int find_distance(int link[100][100],int start,int dest,int n,int e)
{
start=start-1;
dest=dest-1;
if(start==dest)return 0;
int visited[100];
int distance;
for(int i=0;i<n;i++)
{
visited[i]=0;
}
stack<int>s;
int k;s.push(start);
visited[start]=1;
bool found=false;
int count =0;
while(!s.empty())
{
k=s.top();
int i;
int check_point=1;
for(i=0;i<n;i++)
{
if(link[k][i]==1 && visited[i]!=1)
{
s.push(i);
count ++;
check_point=0;
if(i==dest)
{
cout<<"found";
found=true;
}
break;
}
}
if(check_point==1)
{
s.pop();
count--;
}
if(found)break;
}
return count;
}
int main()
{
int n,e,a,b;
int link[100][100];
cout<<"enter the number of vertices and edges";
// cin>>n>>e;
n=5;e=4;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
link[i][j]=0;
else
link[i][j]=INT_MAX;
cout<<link[i][j]<<" ";
}
cout<<endl;
}
int input[4][2]={{1,2},{1,3},{2,4},{2,5}};
for(int i=0;i<e;i++)
{
a=input[i][0];
b=input[i][1];
link[a-1][b-1]=1;
link[b-1][a-1]=1;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<link[i][j]<<" ";
}
cout<<endl;
}
while(true) {
cout<<endl<<"enter the starting point .. ";
int start;
cin>>start;
int dest;
cout<<endl<<"enter the destination point .. ";
cin>>dest;
int distance = find_distance(link,start,dest,n,e);
cout<<endl<<"distance is "<<distance;
}
return 0;
}

Converting mql4 EA to mql5

I have been trying to figure out how to change my MQL4 code to MQL5. So far I've been able to change the RSI and MACD conditions and SendOrder() but there's a lot, like the ModifyOrder() and CloseOrder() amongst other stuff that I've not been able to do to complete it. I know this is a mouthful but I would really appreciate some help in completing this.
This is the original MQL4 code:
extern int MagicNumber=112223;
extern double Lots =0.005;
extern double StopLoss=0;
extern double TakeProfit=0;
extern int TrailingStop=0;
extern int Slippage=3;
int mode_main = 0;
int mode_signal = 1;
//+------------------------------------------------------------------+
// expert start function
//+------------------------------------------------------------------+
int start()
{
double MyPoint=_Point;
if(Digits==3 || Digits==5) MyPoint=Point*10;
double TheStopLoss=0;
double TheTakeProfit=0;
if( TotalOrdersCount()==0 )
{
int result=0;
if((iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_signal,0)<iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_main,0))&&(iRSI(NULL,PERIOD_M5,2,PRICE_CLOSE,0)>84)) // Here is your open buy rule
{
result=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"EA",MagicNumber,0,Blue);
if(result>0)
{
TheStopLoss=0;
TheTakeProfit=0;
if(TakeProfit>0) TheTakeProfit=Ask+TakeProfit*MyPoint;
if(StopLoss>0) TheStopLoss=Ask-StopLoss*MyPoint;
OrderSelect(result,SELECT_BY_TICKET);
OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green);
}
return(0);
}
if((iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_main,0)<iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_signal,0))&&(iRSI(NULL,PERIOD_M5,2,PRICE_CLOSE,0)<16)) // Here is your open Sell rule
{
result=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"EA",MagicNumber,0,Red);
if(result>0)
{
TheStopLoss=0;
TheTakeProfit=0;
if(TakeProfit>0) TheTakeProfit=Bid-TakeProfit*MyPoint;
if(StopLoss>0) TheStopLoss=Bid+StopLoss*MyPoint;
OrderSelect(result,SELECT_BY_TICKET);
OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green);
}
return(0);
}
}
for(int cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber
)
{
if(OrderType()==OP_BUY)
{
if((iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_signal,0)>iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_main,0))&&(iRSI(NULL,PERIOD_M5,2,PRICE_OPEN,0)<16)) //here is your close buy rule
{
OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,Red);
}
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>MyPoint*TrailingStop)
{
if(OrderStopLoss()<Bid-MyPoint*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MyPoint,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else
{
if((iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_main,0)>iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,mode_signal,0))&&(iRSI(NULL,PERIOD_M5,2,PRICE_OPEN,0)>84)) // here is your close sell rule
{
OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,Red);
}
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(MyPoint*TrailingStop))
{
if((OrderStopLoss()>(Ask+MyPoint*TrailingStop)) || (OrderStopLoss()==0))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+MyPoint*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}
return(0);
}
int TotalOrdersCount()
{
int result=0;
for(int i=0;i<OrdersTotal();i++)
{
OrderSelect(i,SELECT_BY_POS ,MODE_TRADES);
if (OrderMagicNumber()==MagicNumber) result++;
}
return (result);
}
Here is what I've done so far (MQL5):
#include <indicators/indicators.mqh>
CIndicators g_indicators;
CiRSI *g_rsi;
CiMACD *g_macd;
input int MagicNumber=112223;
input double Lots =0.005;
input double StopLoss=0;
input double TakeProfit=0;
input int TrailingStop=0;
input int Slippage=3;
int OnInit() {
g_rsi = new CiRSI();
g_indicators.Add(g_rsi);
g_macd = new CiMACD();
g_indicators.Add(g_macd);
bool is_init = g_rsi.Create(_Symbol, PERIOD_M5, 2, PRICE_CLOSE);
is_init &= g_macd.Create(_Symbol, PERIOD_M5, 12, 26, 9, PRICE_CLOSE);
return is_init ? INIT_SUCCEEDED : INIT_FAILED;
}
void OnTick() {
g_indicators.Refresh();
double MyPoint=_Point;
if(_Digits==3 || _Digits==5) MyPoint=_Point*10;
double TheStopLoss=0;
double TheTakeProfit=0;
if( TotalOrdersCount()==0 )
{
int result=0;
if (g_macd.Main(0) > g_macd.Signal(0) && g_rsi.Main(0) > 84) { // Here is your open Buy rule
Print("Signal!");
MqlTradeRequest request;
MqlTradeResult result;
MqlTradeCheckResult check;
ZeroMemory(request);
ZeroMemory(result);
ZeroMemory(check);
double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits); // Get the Ask Price
//--- parameters of request
request.action =TRADE_ACTION_PENDING; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =Lots; // volume of 0.005 lot
request.type =ORDER_TYPE_BUY; // order type
request.price = Ask; // price for opening
request.deviation=0; // allowed deviation from the price
request.magic =magicnumber; // MagicNumber of the order
request.tp = 0;
request.sl = 0;
request.type_filling=ORDER_FILLING_RETURN;
request.type_time=0;
request.expiration=0;
ObjectSetString(0,name,OBJPROP_TEXT,string(result.order));
if(!OrderSend(request,result))
{
Print(__FUNCTION__,": error ",GetLastError(),", retcode = ",result.retcode);
}
}
}
if (g_macd.Main(0) < g_macd.Signal(0) && g_rsi.Main(0) < 16) { // Here is your open Sell rule
Print("Signal!");
MqlTradeRequest request;
MqlTradeResult result;
MqlTradeCheckResult check;
ZeroMemory(request);
ZeroMemory(result);
ZeroMemory(check);
double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits); // Get the Bid Price
//--- parameters of request
request.action =TRADE_ACTION_PENDING; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =Lots; // volume of 0.005 lot
request.type =ORDER_TYPE_SELL; // order type
request.price = Bid; // price for opening
request.deviation=0; // allowed deviation from the price
request.magic =magicnumber; // MagicNumber of the order
request.tp = 0;
request.sl = 0;
request.type_filling=ORDER_FILLING_RETURN;
request.type_time=0;
request.expiration=0;
ObjectSetString(0,name,OBJPROP_TEXT,string(result.order));
if(!OrderSend(request,result))
{
Print(__FUNCTION__,": error ",GetLastError(),", retcode = ",result.retcode);
}
}
}
}
}
Thanks in advance.
Yes, it may take long. luckily, someone wrote a library that you are welcome to download from https://www.mql5.com/ru/code/16006.
#include <MT4Orders.mqh> // if you have #include <Trade/Trade.mqh> in your MQL5 files, include this one AFTER.
int ticket = OrderSend(...);
same for `OrderModify()` and `OrderDelete` \ `OrderModify`
Keep in mind that this lib works for hedging mode only, so your MT5 must have a hedging mode.
full example below:
#include <MT45/MT4Orders.mqh>
//better to use MQL5 analogues of Ask etc for both MQL4 and MQL5, or redefine them
#define Ask SymbolInfoDouble(_Symbol,SYMBOL_ASK)
#define Bid SymbolInfoDouble(_Symbol,SYMBOL_BID)
#define Point _Point
#define Digits _Digits
// your inputs
extern int MagicNumber=112223;
extern double Lots =0.005;
extern double StopLoss=0;
extern double TakeProfit=0;
extern int TrailingStop=0;
extern int Slippage=3;
//int mode_main = 0; //probably throw this away
//int mode_signal = 1; //probably throw this away
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//initialize your indicators here
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//deinitialize your indicators here if you need to avoid memory leak
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
double MyPoint=_Point;
if(Digits==3 || Digits==5) MyPoint=Point*10;
double TheStopLoss=0;
double TheTakeProfit=0;
if( TotalOrdersCount()==0 )
{
TICKET_TYPE result=0;
if(isRule4Buy()) // Here is your open buy rule
{
result=OrderSend(Symbol(),OP_BUY,Lots,SymbolInfoDouble(_Symbol,SYMBOL_ASK),Slippage,0,0,"EA",MagicNumber,0,clrBlue);
if(result>0)
{
TheStopLoss=0;
TheTakeProfit=0;
if(TakeProfit>0) TheTakeProfit=Ask+TakeProfit*MyPoint;
if(StopLoss>0) TheStopLoss=Ask-StopLoss*MyPoint;
OrderSelect(result,SELECT_BY_TICKET);
OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green);
}
return;
}
if(isRule4Sell())
{
//simply copy the sell block
}
}
for(int cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber
)
{
if(OrderType()==OP_BUY)
{
if(isRule4Sell())
{
OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,Red);
}
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>MyPoint*TrailingStop)
{
if(OrderStopLoss()<Bid-MyPoint*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MyPoint,OrderTakeProfit(),0,Green);
return;
}
}
}
}
else
{
//simply copy the sell block
}
}
}
}
//+------------------------------------------------------------------+
int TotalOrdersCount()
{
int result=0;
for(int i=0;i<OrdersTotal();i++)
{
OrderSelect(i,SELECT_BY_POS ,MODE_TRADES);
if (OrderMagicNumber()==MagicNumber) result++;
}
return (result);
}
//+------------------------------------------------------------------+
bool isRule4Buy()
{
#ifdef __MQL4__
return iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0)<iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_MAIN,0)
&& iRSI(NULL,PERIOD_M5,2,PRICE_CLOSE,0)>84;
#else
return true;
//replace with MT5
//g_macd.Main(0) > g_macd.Signal(0) && g_rsi.Main(0) > 84
#endif
}
bool isRule4Sell()
{
//similar for sell
return false;
}

How to restart a sketch project in processing?

I am working on a Processing project, but I donĀ“t know how to restart the project once it is over. I have searched and found that the setup() method will make it. But it's not working. Can anyone help me. I would like the sketch to restart by itself once it is finished.
/* OpenProcessing Tweak of *#*http://www.openprocessing.org/sketch/59807*#* */
/* !do not delete the line above, required for linking your tweak if you upload again */
//
// outline: takes an image (image.jpg) and creates a sketch version
//
// procsilas (procsilas#hotmail.com / http://procsilas.net)
//
String iName="image.jpeg";
void setup() {
llegeixImatge("./"+iName);
size(img.width, img.height);
}
// parameters
// NO real control, so be careful
int NP=6000; // 1000 for line art, 10000 for complex images, O(N^2) so be patient!!!
int B=1; // try 2 or 3
float THR=28; // range 5-50
float MD=6; // range 0-10
int NMP=6; // range 1-15
float[][] punts;
color[] cpunts;
int [] usat;
int [] NmP=new int[NMP];
float [] NdmP=new float[NMP];
int inici=0;
PImage img;
void llegeixImatge(String s) {
img = loadImage(s);
img.loadPixels();
}
float fVar(int x, int y) {
// neighborhood 2B+1x2B+1 pixels
float m=0;
for (int k1=-B; k1<=B; k1++) {
for (int k2=-B; k2<=B; k2++) {
color c=img.pixels[(y+k1)*img.width+(x+k2)];
m+=brightness(c);
}
}
m/=float((2*B+1)*(2*B+1));
float v=0;
for (int k1=-B; k1<B; k1++) {
for (int k2=-B; k2<B; k2++) {
color c=img.pixels[(y+k1)*img.width+(x+k2)];
v+=(brightness(c)-m)*(brightness(c)-m);
}
}
v=sqrt(v)/(float) (2*B+1);
return v;
}
void creaPunts() {
punts = new float[NP][2];
cpunts = new color[NP];
usat = new int[NP];
int nint1=0;
int nint2=0;
for (int i=0; i<NP;) {
int x=B+int(random(width-2*B));
int y=B+int(random(height-2*B));
//println(i+" = "+x+", "+y+": "+THR+", "+MD);
// points need to be at least MD far from each other
int flag=0;
if (MD>0.0) {
for (int j=0; flag==0 && j<i; j++) {
if (dist(x, y, punts[j][0], punts[j][1])<MD) {
flag=1;
}
}
}
if (flag==0) {
nint1=0;
float f=fVar(x, y);
// use only "valid" points
if (f>=THR) {
nint2=0;
punts[i][0]=x;
punts[i][1]=y;
cpunts[i]=img.pixels[y*img.width+x];
usat[i]=0;
i++;
}
else {
nint2++;
if (nint2>=10) {
THR/=(1+1.0/float(NP-i));
MD/=(1+1.0/float(NP-i));
nint2=0;
}
}
}
else {
nint1++;
if (nint1>=10) {
MD/=2.0;
THR*=1.618;
nint1=0;
}
}
}
}
int NessimMesProper(int i) {
if (NMP<=1) {
int mP=-1;
float dmP=dist(0, 0, width, height);
for (int j=0; j<NP; j++) {
if (usat[j]==0) {
float jmP=dist(punts[i][0], punts[i][1], punts[j][0], punts[j][1]);
if (jmP<dmP) {
dmP=jmP;
mP=j;
}
}
}
return mP;
}
else {
for (int j=0; j<NMP; j++) {
NmP[j]=-1;
NdmP[j]=dist(0, 0, width, height);
}
for (int j=0; j<NP; j++) {
if (usat[j]==0) {
float jmP=dist(punts[i][0], punts[i][1], punts[j][0], punts[j][1]);
int k=NMP;
while(k>0 && NdmP[k-1]>jmP) {
k--;
}
if (k<NMP) {
for (int l=0; l<(NMP-k)-1; l++) {
NmP[(NMP-1)-l]=NmP[(NMP-1)-(l+1)];
NdmP[(NMP-1)-l]=NdmP[(NMP-1)-(l+1)];
}
NmP[k]=j;
NdmP[k]=jmP;
}
}
}
return NmP[NMP-1];
}
}
int fase=0;
void draw() {
if (fase==0) {
creaPunts();
background(#FFFFFF);
fase=1;
}
else {
if (inici!=-1) {
stroke(#000000);
usat[inici]=1;
int seguent=NessimMesProper(inici);
if (seguent!=-1) {
line(punts[inici][0], punts[inici][1], punts[seguent][0], punts[seguent][1]);
}
inici=seguent;
}
else {
//save("outline_"+iName);
}
}
}
You should not call setup() yourself.
Step 1: Encapsulate the state of your program in a set of variables.
Step 2: Use those variables to draw your sketch.
Step 3: Modify those variables to change what's being drawn.
Step 4: Simply reset those variables to their initial values when you want to reset the sketch.
Here's an example program that stores its state (the positions the user has clicked) in an ArrayList. It uses that ArrayList to draw the sketch, and new points are added whenever the user clicks. When the user types a key, the sketch is reset by clearing out the ArrayList:
ArrayList<PVector> points = new ArrayList<PVector>();
void setup(){
size(500, 500);
}
void draw(){
background(0);
for(PVector p : points){
ellipse(p.x, p.y, 20, 20);
}
}
void mousePressed(){
points.add(new PVector(mouseX, mouseY));
}
void keyPressed(){
points.clear();
}

Shoot balloons and Collect Maximum Points

There are 10 balloons and each balloon has some point written onto it. If a customer shoots a balloon, he will get points equal to points on left balloon multiplied by points on the right balloon. A Customer has to collect maximum points in order to win this game. What will be maximum points and in which order should he shoot balloons to get maximum points ?
Please note that if there is only one balloon then you return the points on that balloon.
I am trying to check all 10! permutations in order to find out maximum points. Is there any other way to solve this in efficient way ?
As i said in the comments a Dynamic programming solution with bitmasking is possible, what we can do is keep a bitmask where a 1 at a bit indexed at i means that the ith baloon has been shot, and a 0 tells that it has not been shot.
So a Dynamic Programming state of only mask is required, where at each state we can transition to the next state by iterating over all the ballons that have not been shot and try to shoot them to find the maximum.
The time complexity of such a solution would be : O((2^n) * n * n) and the space complexity would be O(2^n).
Code in c++, it is not debugged you may need to debug it :
int n = 10, val[10], dp[1024]; //set all the values of dp table to -1 initially
int solve(int mask){
if(__builtin_popcount(mask) == n){
return 0;
}
if(dp[mask] != -1) return dp[mask];
int prev = 1, ans = 0;
for(int i = 0;i < n;i++){
if(((mask >> i) & 1) == 0){ //bit is not set
//try to shoot current baloon
int newMask = mask | (1 << i);
int fwd = 1;
for(int j = i+1;j < n;j++){
if(((mask >> j) & 1) == 0){
fwd = val[j];
break;
}
}
ans = max(ans, solve(newMask) + (prev * fwd));
prev = val[i];
}
}
return dp[mask] = ans;
}
#include<iostream>
using namespace std;
int findleft(int arr[],int n,int j ,bool isBurst[],bool &found)
{
if(j<=0)
{
found=false;
return 1;
}
for(int i=j-1;i>=0;i--)
{
if(!isBurst[i])
{
return arr[i];
}
}
found = false;
return 1;
}
int findright(int arr[],int n,int j,bool isBurst[],bool &found)
{
if(j>=n)
{
found = false;
return 1;
}
for(int i= j+1;i<=n;i++)
{
if(!isBurst[i])
{
return arr[i];
}
}
found=false;
return 1;
}
int calc(int arr[],int n,int j,bool isBurst[])
{
int points =0;
bool leftfound=true;
bool rightfound=true;
int left= findleft( arr, n-1, j,isBurst , leftfound);
int right = findright( arr,n-1, j,isBurst, rightfound);
if(!leftfound && !rightfound)
{
points+=arr[j];
}
else
{
points+=left*right*arr[j];
}
return points;
}
void maxpoints(int arr[],int n,int cp,int curr_ans,int &ans,int count,bool isBurst[])
{
if(count==n)
{
if(curr_ans>ans)
{
ans=curr_ans;
return;
}
}
for(int i=0;i<n;i++)
{
if(!isBurst[i])
{
isBurst[i]=true;
maxpoints(arr,n,i,curr_ans+calc(arr,n,i,isBurst),ans,count+1,isBurst);
isBurst[i]=false;
}
}
}
int main()
{
int n;
cin>>n;
int ans=0;
int arr[n];
bool isBurst[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
isBurst[i]=false;
}
maxpoints(arr,n,0,0,ans,0,isBurst);
cout<<ans;
return 0;
}

2D vector subscript out of range

It says vector subscript out of range when achieving if statement. I think I added extra int to floor, or extra floor vector to 2D vector. I am using VS 2010(C++)
I tried to find it on other questions but not succeeded.
bool is_perfect_square(int);
int main()
{
int cust;
vector<int>floor;
vector<vector<int>>hotel;
floor.push_back(0);
hotel.push_back(floor);
hotel[0][0]=1;
for(cust=2; ; cust++)
{
for(int i=0; i<=hotel.size(); i++)
{
if(is_perfect_square(cust+hotel[i][floor.size()]))
{
floor.push_back(0);
hotel[i][cust]=cust;
break;
}
else
{
hotel.push_back(floor);
hotel[hotel.size()][0]=cust;
}
}
}
int sum=0;
for(int a=1; a<=hotel.size(); a++)
{
for(int b=1; b<=floor.size(); b++)
{
if(pow(a-1,2)+pow(b-1,2)==14234886498625)
sum+=hotel[a-1][b-1];
}
}
cout<<sum<<endl;
system("pause");
return 0;
}
bool is_perfect_square(int n)
{
int root=floor(sqrt(n));
return n == root * root;
}
I put my answers in the comments.
bool is_perfect_square(int);
int main()
{
int cust;
vector<int>floor;
vector<vector<int>>hotel;
floor.push_back(0);
hotel.push_back(floor);
hotel[0][0]=1;
// you may not be able to get out of this loop
// because the "break" below only exits one level of the loop.
for(cust=2; ; cust++)
{
// this should be changed to "i<hotel.size()",
// because the subscript of a vector ranges from 0 to its size minus one.
for(int i=0; i<=hotel.size(); i++)
{
// here "floor.size()" should be floor.size() - 1, the same reason.
if(is_perfect_square(cust+hotel[i][floor.size()]))
{
floor.push_back(0);
hotel[i][cust]=cust;
break;
}
else
{
hotel.push_back(floor);
hotel[hotel.size()][0]=cust;
}
}
}
int sum=0;
for(int a=1; a<=hotel.size(); a++)
{
for(int b=1; b<=floor.size(); b++)
{
if(pow(a-1,2)+pow(b-1,2)==14234886498625)
sum+=hotel[a-1][b-1];
}
}
cout<<sum<<endl;
system("pause");
return 0;
}
bool is_perfect_square(int n)
{
int root=floor(sqrt(n));
return n == root * root;
}

Resources