I am trying to code a hedging EA on mql5 but some function is not working - algorithmic-trading

`//so I am coding this EA on MQL5 and everything works fine until its time to to hedge. look at the //code
void onTick{
safetyBuy()
}
void safetyBuy(){
double openPrice;
int PositionDirection;
string TP;
string sl;
string volume;
double secondaryVolume = ReturnVolume("buy");
ObjectGetString(_Symbol,"TP points",OBJPROP_TEXT,0,TP);
ObjectGetString(_Symbol,"stopLoss",OBJPROP_TEXT,0,sl);
ObjectGetString(_Symbol,"volume", OBJPROP_TEXT,0,volume);
for(int i = PositionsTotal() - 1; i>=0; i--){
if(PositionsTotal()>0){
ulong PositionTicket = PositionGetTicket(i);
PositionDirection =(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(PositionDirection == POSITION_TYPE_BUY){
openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
}
}
}
if(ReturnVolume("sell") > ReturnVolume("Buy") && OrdersTotal() == 0){
trade.BuyLimit(secondaryVolume, openPrice, _Symbol, 0,0,ORDER_TIME_GTC,0,NULL);
}
}
double ReturnVolume(string postype){
double TradeVolume;
int PositionDirection;
ulong PositionTicket;
for(int i = PositionsTotal() - 1; i>=0; i--){
PositionTicket = PositionGetTicket(i);
PositionDirection =(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(postype == "buy" && PositionDirection == POSITION_TYPE_BUY){
TradeVolume += PositionGetDouble(POSITION_VOLUME);
}
if(postype == "sell" && PositionDirection == POSITION_TYPE_SELL){
TradeVolume += PositionGetDouble(POSITION_VOLUME);
}
}
return TradeVolume;
}
the problem is when I am testing my EA when the buy limit order is supposed to open nothing happens and I checked the journal to see for runtime errors but there are none its as if the program doesnt see my instructions, any help would be appreciated. Thanks in advance. (ps the ReturnVolume function works as intended just included it for more clarity)
`

Related

Binary Search Symbol Table implementation going inside infinite loop

I am trying to implement 'Binary Search in an ordered array' from the book 'Algorithms (fourth edition) by Robert Sedgewick & Kevin Wayne' (on page 381). However my code is going inside infinite loop. Please help. Below is the code:
public class BinarySearchST<Key extends Comparable<Key>, Value>{
private Key keys[];
private Value values[];
private int N;
public BinarySearchST(int capacity){
keys = (Key[]) new Comparable[capacity];
values = (Value[]) new Object[capacity];
}
public int size(){
return N;
}
public boolean isEmpty(){
return N == 0;
}
public int rank(Key key){
int lo = 0, hi = N-1;
while(lo <= hi){
int mid = (lo + (hi - lo))/2;
int comp = key.compareTo(keys[mid]);
if(comp < 0) hi = mid - 1;
else if(comp > 0) lo = mid + 1;
else return mid;
}
return lo;
}
public Value get(Key key){
if(isEmpty()) return null;
int rank = rank(key);
if(rank < N && key.compareTo(keys[rank]) == 0)
return values[rank];
else
return null;
}
public void put(Key key, Value value){
int rank = rank(key);
if(rank < N && key.compareTo(keys[rank]) == 0){//key already existing, just update value.
values[rank] = value;
return;
}
for(int i = N; i > rank; i--){
keys[i] = keys[i-1]; values[i] = values[i-1];
}
keys[rank] = key;
values[rank] = value;
N++;
}
public static void main(String[] args){
BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(10);
st.put("A", 10);
st.put("B", 100);
st.put("C", 1000);
StdOut.println(st.get("A"));
}
}
This appears to be correct to me, but looks like some issue inside put() for loop.
use int mid = (lo + hi)/2.
You are using int mid = (lo+(hi-lo))/2 which reduces to hi/2. So, eventually your middle will be less than your lo and will not converge causing infinite loop.

IndexOutOfBoundsException when I attempt to use list.contain(...), not sure how to fix

public static void main(String[] args) {
List<String> stuff = new ArrayList<String>();
List<String> fc = new ArrayList<String>();
List<String> on = new ArrayList<String>();
List<String> done = new ArrayList<String>();
int d=0;
int x=0;
int r=0;
//"inputs" is an array with all the inputs from the user.
//You will have to go through and extract the data from "inputs" and store it in
//a data type that works
Scanner in = new Scanner(System.in);
int inputs_size = 0;
inputs_size = 100;
String[] inputs = new String[inputs_size];
for(int i = 0; i < inputs_size; i++) {
String inputs_item;
try {
inputs_item = in.nextLine();
} catch (Exception e) {
inputs_item = null;
}
inputs[i] = inputs_item;
}
for(int n=0; n<inputs.length-1; n++){
if(inputs[n]==null){
break;
}
stuff.add(inputs[n]);
}
while(d<stuff.size()){
if(stuff.get(d).equals("0")){
x++;
}
d++;
}
for(int t=0; t<stuff.size(); t++){
if(stuff.get(t).equals("0")){
break;
}
fc.add(stuff.get(t));
}
r=fc.size();
while(r<stuff.size()-1){
if(stuff.get(r).equals("0")){
r++;
x=x-1;
}
if(x==4 && stuff.get(r)!="0"){
on.add(stuff.get(r));
}
if(x==3 && stuff.get(r)!="0"){
tw.add(stuff.get(r));
}
if(x==2 && stuff.get(r)!="0"){
th.add(stuff.get(r));
}
if(x==1 && stuff.get(r)!="0"){
fo.add(stuff.get(r));
}
if(x==0 && stuff.get(r)!="0"){
fi.add(stuff.get(r));
}
if(x==-1 && stuff.get(r)!="0"){
si.add(stuff.get(r));
}
r++;
}
int z=0;
int counter = 1;
for(; counter < fc.size(); counter++) {
if(counter>fc.size()){
break;
}
**if(fc.contains(on.get(counter)))** {
z=0;
}
else{
z=1;
break;
}
}
if(z==0){
done.add(on.get(0));
}
counter=1;
z=0;
System.out.println(done);
}
}
I am getting an IndexOutOfBounds error for the line of code with the asterisks around it (fc.contains(...)). I am attempting to create a program that acts as a fridge, receives input and determines what recipes I am capable of making.
Example input:
(milk
cheese
eggs
honey) -ingredients in fridge
(0) -separates lists
(eggs and honey) -recipe in question
(eggs
honey) -ingredients required for recipe, are they in fridge?? yes
So my output would be: Eggs and Honey, or the names of the recipes I can make.
Where did I go wrong here? Thank you!
Following your code, I think your on array is null.
Look:
if(x==4 && stuff.get(r)!="0"){
on.add(stuff.get(r));
}
It is the only time you try to add something to your on. And your fc and stuff size will be the same, since you doesn't have something to make it different (instead of this .equals("0"), but if you enter anything else, it will be the same). After that, we have:
r=fc.size();
while(r<stuff.size()-1){
We know that fc and stuff have the same size, then r won't be lower than stuff.size()-1.
By not entering the loop, it will remains null. So any .get() will result in IndexOutOfBounds.

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;
}

Debug Assertion Error as soon as I take the input. Something wrong with "delete"?

I am having debug assertion error as soon as I input two elements. The program was giving me access reading or sometimes writing violation error after taking 7-8 entries but after I deleted the dynamic array, it is showing debug assertion failed after taking first two inputs and breaks down. Any idea for how to solve it? I am copying only my air class here. I have similar Fire, earth and water classes too.
The error is BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Someone else too asked this question but i can't figure out My program errors. Kindly help would be appreciated.
#ifndef AIR_H
#define AIR_H
#include <iostream>
#include <string>
#include "element.h"
using namespace std;
class Air :public Element
{
public:
string air;
string Elements [2];
int i;
string *elements;
public:
Air(string n): Element (n)
{
air = n;
i=-1;
elements = new string[2];
}
void alreadyExists (string a)
{
int lineCount = 0;
ifstream read;
read.open ("Air.txt", ios::in | ios::app);
while(!read.eof())
{
string x;
read>>x;
lineCount++;
}
lineCount--;
read.close();
read.open("Air.txt", ios::in|ios::app);
for(int i = 0; i < lineCount; i++)
{
read>>elements[i];
}
bool Found = false;
for(int i = 0; i < lineCount; i++) {
if(a == elements[i])
{
Found = true;
break;
}
}
if(!Found)
{
write2file (a);
}
}
void write2file (string air)
{
ofstream write;
write.open ("Air.txt", ios::out|ios::app);
{
write<<air<<endl;
}
}
void DisplayA ()
{
/*for(int i=0; i<2; i++)//( to read through the arrays )
{
cout<<Elements[i]<<endl;
}*/
ifstream read ("Air.txt", ios::in|ios::app);
int i=0;
while (read >> Elements[i])
{
cout<<Elements[i]<<endl;
}
}
Air operator+(Air & air)
{
Air newElement ("NULL");
if (this->air == "Air"||this->air=="air"&& air.air == "Air"||air.air=="air")
{
newElement.air = "Pressure";
cout<<"Yay!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else if ((this->air == "Air"||this->air == "air") && (air.air == "Pressure"||air.air=="pressure"))/* || ((this->air == "Pressure"||this->air=="pressure") && ( air.air == "Air"||air.air=="air")))*/
{
newElement.air = "Atmosphere";
cout<<"Wuhooo!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else return newElement;
}//pressure, atmosphere
~ Air ()
{
delete []elements;
}
};
#endif
BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Assertion means a corrupt heap at deleting/clearing.
As far as I see, you missed the virtual deconstructor of Element.
Try something like:
virtual ~Element() {}
in class Element.
And please post also the Element class.
Good luck!

Reverse the ordering of words in a string

I have this string s1 = "My name is X Y Z" and I want to reverse the order of the words so that s1 = "Z Y X is name My".
I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data structures) and with the time complexity being O(n)?
Reverse the entire string, then reverse the letters of each individual word.
After the first pass the string will be
s1 = "Z Y X si eman yM"
and after the second pass it will be
s1 = "Z Y X is name My"
reverse the string and then, in a second pass, reverse each word...
in c#, completely in-place without additional arrays:
static char[] ReverseAllWords(char[] in_text)
{
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);
//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}
return in_text;
}
static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}
Not exactly in place, but anyway: Python:
>>> a = "These pretzels are making me thirsty"
>>> " ".join(a.split()[::-1])
'thirsty me making are pretzels These'
In Smalltalk:
'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]
I know noone cares about Smalltalk, but it's so beautiful to me.
You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered "in place", but it's not completely "extra data structure free".
Below is code implementing what Bill the Lizard describes:
string words = "this is a test";
// Reverse the entire string
for(int i = 0; i < strlen(words) / 2; ++i) {
char temp = words[i];
words[i] = words[strlen(words) - i];
words[strlen(words) - i] = temp;
}
// Reverse each word
for(int i = 0; i < strlen(words); ++i) {
int wordstart = -1;
int wordend = -1;
if(words[i] != ' ') {
wordstart = i;
for(int j = wordstart; j < strlen(words); ++j) {
if(words[j] == ' ') {
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = strlen(words);
for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
char temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
}
}
What language?
If PHP, you can explode on space, then pass the result to array_reverse.
If its not PHP, you'll have to do something slightly more complex like:
words = aString.split(" ");
for (i = 0; i < words.length; i++) {
words[i] = words[words.length-i];
}
public static String ReverseString(String str)
{
int word_length = 0;
String result = "";
for (int i=0; i<str.Length; i++)
{
if (str[i] == ' ')
{
result = " " + result;
word_length = 0;
} else
{
result = result.Insert(word_length, str[i].ToString());
word_length++;
}
}
return result;
}
This is C# code.
In Python...
ip = "My name is X Y Z"
words = ip.split()
words.reverse()
print ' '.join(words)
Anyway cookamunga provided good inline solution using python!
This is assuming all words are separated by spaces:
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "What are you looking at";
int i, n = strlen(string);
int tail = n-1;
for(i=n-1;i>=0;i--)
{
if(string[i] == ' ' || i == 0)
{
int cursor = (i==0? i: i+1);
while(cursor <= tail)
printf("%c", string[cursor++]);
printf(" ");
tail = i-1;
}
}
return 0;
}
class Program
{
static void Main(string[] args)
{
string s1 =" My Name varma:;
string[] arr = s1.Split(' ');
Array.Reverse(arr);
string str = string.Join(" ", arr);
Console.WriteLine(str);
Console.ReadLine();
}
}
This is not perfect but it works for me right now. I don't know if it has O(n) running time btw (still studying it ^^) but it uses one additional array to fulfill the task.
It is probably not the best answer to your problem because i use a dest string to save the reversed version instead of replacing each words in the source string. The problem is that i use a local stack variable named buf to copy all the words in and i can not copy but into the source string as this would lead to a crash if the source string is const char * type.
But it was my first attempt to write s.th. like this :) Ok enough blablub. here is code:
#include <iostream>
using namespace std;
void reverse(char *des, char * const s);
int main (int argc, const char * argv[])
{
char* s = (char*)"reservered. rights All Saints. The 2011 (c) Copyright 11/10/11 on Pfundstein Markus by Created";
char *x = (char*)"Dogfish! White-spotted Shark, Bullhead";
printf("Before: |%s|\n", x);
printf("Before: |%s|\n", s);
char *d = (char*)malloc((strlen(s)+1)*sizeof(char));
char *i = (char*)malloc((strlen(x)+1)*sizeof(char));
reverse(d,s);
reverse(i,x);
printf("After: |%s|\n", i);
printf("After: |%s|\n", d);
free (i);
free (d);
return 0;
}
void reverse(char *dest, char *const s) {
// create a temporary pointer
if (strlen(s)==0) return;
unsigned long offset = strlen(s)+1;
char *buf = (char*)malloc((offset)*sizeof(char));
memset(buf, 0, offset);
char *p;
// iterate from end to begin and count how much words we have
for (unsigned long i = offset; i != 0; i--) {
p = s+i;
// if we discover a whitespace we know that we have a whole word
if (*p == ' ' || *p == '\0') {
// we increment the counter
if (*p != '\0') {
// we write the word into the buffer
++p;
int d = (int)(strlen(p)-strlen(buf));
strncat(buf, p, d);
strcat(buf, " ");
}
}
}
// copy the last word
p -= 1;
int d = (int)(strlen(p)-strlen(buf));
strncat(buf, p, d);
strcat(buf, "\0");
// copy stuff to destination string
for (int i = 0; i < offset; ++i) {
*(dest+i)=*(buf+i);
}
free(buf);
}
We can insert the string in a stack and when we extract the words, they will be in reverse order.
void ReverseWords(char Arr[])
{
std::stack<std::string> s;
char *str;
int length = strlen(Arr);
str = new char[length+1];
std::string ReversedArr;
str = strtok(Arr," ");
while(str!= NULL)
{
s.push(str);
str = strtok(NULL," ");
}
while(!s.empty())
{
ReversedArr = s.top();
cout << " " << ReversedArr;
s.pop();
}
}
This quick program works..not checks the corner cases though.
#include <stdio.h>
#include <stdlib.h>
struct node
{
char word[50];
struct node *next;
};
struct stack
{
struct node *top;
};
void print (struct stack *stk);
void func (struct stack **stk, char *str);
main()
{
struct stack *stk = NULL;
char string[500] = "the sun is yellow and the sky is blue";
printf("\n%s\n", string);
func (&stk, string);
print (stk);
}
void func (struct stack **stk, char *str)
{
char *p1 = str;
struct node *new = NULL, *list = NULL;
int i, j;
if (*stk == NULL)
{
*stk = (struct stack*)malloc(sizeof(struct stack));
if (*stk == NULL)
printf("\n####### stack is not allocated #####\n");
(*stk)->top = NULL;
}
i = 0;
while (*(p1+i) != '\0')
{
if (*(p1+i) != ' ')
{
new = (struct node*)malloc(sizeof(struct node));
if (new == NULL)
printf("\n####### new is not allocated #####\n");
j = 0;
while (*(p1+i) != ' ' && *(p1+i) != '\0')
{
new->word[j] = *(p1 + i);
i++;
j++;
}
new->word[j++] = ' ';
new->word[j] = '\0';
new->next = (*stk)->top;
(*stk)->top = new;
}
i++;
}
}
void print (struct stack *stk)
{
struct node *tmp = stk->top;
int i;
while (tmp != NULL)
{
i = 0;
while (tmp->word[i] != '\0')
{
printf ("%c" , tmp->word[i]);
i++;
}
tmp = tmp->next;
}
printf("\n");
}
Most of these answers fail to account for leading and/or trailing spaces in the input string. Consider the case of str=" Hello world"... The simple algo of reversing the whole string and reversing individual words winds up flipping delimiters resulting in f(str) == "world Hello ".
The OP said "I want to reverse the order of the words" and did not mention that leading and trailing spaces should also be flipped! So, although there are a ton of answers already, I'll provide a [hopefully] more correct one in C++:
#include <string>
#include <algorithm>
void strReverseWords_inPlace(std::string &str)
{
const char delim = ' ';
std::string::iterator w_begin, w_end;
if (str.size() == 0)
return;
w_begin = str.begin();
w_end = str.begin();
while (w_begin != str.end()) {
if (w_end == str.end() || *w_end == delim) {
if (w_begin != w_end)
std::reverse(w_begin, w_end);
if (w_end == str.end())
break;
else
w_begin = ++w_end;
} else {
++w_end;
}
}
// instead of reversing str.begin() to str.end(), use two iterators that
// ...represent the *logical* begin and end, ignoring leading/traling delims
std::string::iterator str_begin = str.begin(), str_end = str.end();
while (str_begin != str_end && *str_begin == delim)
++str_begin;
--str_end;
while (str_end != str_begin && *str_end == delim)
--str_end;
++str_end;
std::reverse(str_begin, str_end);
}
My version of using stack:
public class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
String ns= s.trim();
Stack<Character> reverse = new Stack<Character>();
boolean hadspace=false;
//first pass
for (int i=0; i< ns.length();i++){
char c = ns.charAt(i);
if (c==' '){
if (!hadspace){
reverse.push(c);
hadspace=true;
}
}else{
hadspace=false;
reverse.push(c);
}
}
Stack<Character> t = new Stack<Character>();
while (!reverse.empty()){
char temp =reverse.pop();
if(temp==' '){
//get the stack content out append to StringBuilder
while (!t.empty()){
char c =t.pop();
sb.append(c);
}
sb.append(' ');
}else{
//push to stack
t.push(temp);
}
}
while (!t.empty()){
char c =t.pop();
sb.append(c);
}
return sb.toString();
}
}
Store Each word as a string in array then print from end
public void rev2() {
String str = "my name is ABCD";
String A[] = str.split(" ");
for (int i = A.length - 1; i >= 0; i--) {
if (i != 0) {
System.out.print(A[i] + " ");
} else {
System.out.print(A[i]);
}
}
}
In Python, if you can't use [::-1] or reversed(), here is the simple way:
def reverse(text):
r_text = text.split(" ")
res = []
for word in range(len(r_text) - 1, -1, -1):
res.append(r_text[word])
return " ".join(res)
print (reverse("Hello World"))
>> World Hello
[Finished in 0.1s]
Printing words in reverse order of a given statement using C#:
void ReverseWords(string str)
{
int j = 0;
for (int i = (str.Length - 1); i >= 0; i--)
{
if (str[i] == ' ' || i == 0)
{
j = i == 0 ? i : i + 1;
while (j < str.Length && str[j] != ' ')
Console.Write(str[j++]);
Console.Write(' ');
}
}
}
Here is the Java Implementation:
public static String reverseAllWords(String given_string)
{
if(given_string == null || given_string.isBlank())
return given_string;
char[] str = given_string.toCharArray();
int start = 0;
// Reverse the entire string
reverseString(str, start, given_string.length() - 1);
// Reverse the letters of each individual word
for(int end = 0; end <= given_string.length(); end++)
{
if(end == given_string.length() || str[end] == ' ')
{
reverseString(str, start, end-1);
start = end + 1;
}
}
return new String(str);
}
// In-place reverse string method
public static void reverseString(char[] str, int start, int end)
{
while(start < end)
{
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
Actually, the first answer:
words = aString.split(" ");
for (i = 0; i < words.length; i++) {
words[i] = words[words.length-i];
}
does not work because it undoes in the second half of the loop the work it did in the first half. So, i < words.length/2 would work, but a clearer example is this:
words = aString.split(" "); // make up a list
i = 0; j = words.length - 1; // find the first and last elements
while (i < j) {
temp = words[i]; words[i] = words[j]; words[j] = temp; //i.e. swap the elements
i++;
j--;
}
Note: I am not familiar with the PHP syntax, and I have guessed incrementer and decrementer syntax since it seems to be similar to Perl.
How about ...
var words = "My name is X Y Z";
var wr = String.Join( " ", words.Split(' ').Reverse().ToArray() );
I guess that's not in-line tho.
In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).
#include<stdio.h>
#include<stdlib.h>
main(){
char* a = malloc(1000);
fscanf(stdin, "%[^\0\n]", a);
int x = 0, y;
while(a[x]!='\0')
{
if (a[x]==' ' || a[x]=='\n')
{
x++;
}
else
{
y=x;
while(a[y]!='\0' && a[y]!=' ' && a[y]!='\n')
{
y++;
}
int z=y;
while(x<y)
{
y--;
char c=a[x];a[x]=a[y];a[y]=c;
x++;
}
x=z;
}
}
fprintf(stdout,a);
return 0;
}
It can be done more simple using sscanf:
void revertWords(char *s);
void revertString(char *s, int start, int n);
void revertWordsInString(char *s);
void revertString(char *s, int start, int end)
{
while(start<end)
{
char temp = s[start];
s[start] = s[end];
s[end]=temp;
start++;
end --;
}
}
void revertWords(char *s)
{
int start = 0;
char *temp = (char *)malloc(strlen(s) + 1);
int numCharacters = 0;
while(sscanf(&s[start], "%s", temp) !=EOF)
{
numCharacters = strlen(temp);
revertString(s, start, start+numCharacters -1);
start = start+numCharacters + 1;
if(s[start-1] == 0)
return;
}
free (temp);
}
void revertWordsInString(char *s)
{
revertString(s,0, strlen(s)-1);
revertWords(s);
}
int main()
{
char *s= new char [strlen("abc deff gh1 jkl")+1];
strcpy(s,"abc deff gh1 jkl");
revertWordsInString(s);
printf("%s",s);
return 0;
}
import java.util.Scanner;
public class revString {
static char[] str;
public static void main(String[] args) {
//Initialize string
//str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
//'r', 'l', 'd' };
getInput();
// reverse entire string
reverse(0, str.length - 1);
// reverse the words (delimeted by space) back to normal
int i = 0, j = 0;
while (j < str.length) {
if (str[j] == ' ' || j == str.length - 1) {
int m = i;
int n;
//dont include space in the swap.
//(special case is end of line)
if (j == str.length - 1)
n = j;
else
n = j -1;
//reuse reverse
reverse(m, n);
i = j + 1;
}
j++;
}
displayArray();
}
private static void reverse(int i, int j) {
while (i < j) {
char temp;
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
private static void getInput() {
System.out.print("Enter string to reverse: ");
Scanner scan = new Scanner(System.in);
str = scan.nextLine().trim().toCharArray();
}
private static void displayArray() {
//Print the array
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
In Java using an additional String (with StringBuilder):
public static final String reverseWordsWithAdditionalStorage(String string) {
StringBuilder builder = new StringBuilder();
char c = 0;
int index = 0;
int last = string.length();
int length = string.length()-1;
StringBuilder temp = new StringBuilder();
for (int i=length; i>=0; i--) {
c = string.charAt(i);
if (c == SPACE || i==0) {
index = (i==0)?0:i+1;
temp.append(string.substring(index, last));
if (index!=0) temp.append(c);
builder.append(temp);
temp.delete(0, temp.length());
last = i;
}
}
return builder.toString();
}
In Java in-place:
public static final String reverseWordsInPlace(String string) {
char[] chars = string.toCharArray();
int lengthI = 0;
int lastI = 0;
int lengthJ = 0;
int lastJ = chars.length-1;
int i = 0;
char iChar = 0;
char jChar = 0;
while (i<chars.length && i<=lastJ) {
iChar = chars[i];
if (iChar == SPACE) {
lengthI = i-lastI;
for (int j=lastJ; j>=i; j--) {
jChar = chars[j];
if (jChar == SPACE) {
lengthJ = lastJ-j;
swapWords(lastI, i-1, j+1, lastJ, chars);
lastJ = lastJ-lengthI-1;
break;
}
}
lastI = lastI+lengthJ+1;
i = lastI;
} else {
i++;
}
}
return String.valueOf(chars);
}
private static final void swapWords(int startA, int endA, int startB, int endB, char[] array) {
int lengthA = endA-startA+1;
int lengthB = endB-startB+1;
int length = lengthA;
if (lengthA>lengthB) length = lengthB;
int indexA = 0;
int indexB = 0;
char c = 0;
for (int i=0; i<length; i++) {
indexA = startA+i;
indexB = startB+i;
c = array[indexB];
array[indexB] = array[indexA];
array[indexA] = c;
}
if (lengthB>lengthA) {
length = lengthB-lengthA;
int end = 0;
for (int i=0; i<length; i++) {
end = endB-((length-1)-i);
c = array[end];
shiftRight(endA+i,end,array);
array[endA+1+i] = c;
}
} else if (lengthA>lengthB) {
length = lengthA-lengthB;
for (int i=0; i<length; i++) {
c = array[endA];
shiftLeft(endA,endB,array);
array[endB+i] = c;
}
}
}
private static final void shiftRight(int start, int end, char[] array) {
for (int i=end; i>start; i--) {
array[i] = array[i-1];
}
}
private static final void shiftLeft(int start, int end, char[] array) {
for (int i=start; i<end; i++) {
array[i] = array[i+1];
}
}
Here is a C implementation that is doing the word reversing inlace, and it has O(n) complexity.
char* reverse(char *str, char wordend=0)
{
char c;
size_t len = 0;
if (wordend==0) {
len = strlen(str);
}
else {
for(size_t i=0;str[i]!=wordend && str[i]!=0;i++)
len = i+1;
}
for(size_t i=0;i<len/2;i++) {
c = str[i];
str[i] = str[len-i-1];
str[len-i-1] = c;
}
return str;
}
char* inplace_reverse_words(char *w)
{
reverse(w); // reverse all letters first
bool is_word_start = (w[0]!=0x20);
for(size_t i=0;i<strlen(w);i++){
if(w[i]!=0x20 && is_word_start) {
reverse(&w[i], 0x20); // reverse one word only
is_word_start = false;
}
if (!is_word_start && w[i]==0x20) // found new word
is_word_start = true;
}
return w;
}
c# solution to reverse words in a sentence
using System;
class helloworld {
public void ReverseString(String[] words) {
int end = words.Length-1;
for (int start = 0; start < end; start++) {
String tempc;
if (start < end ) {
tempc = words[start];
words[start] = words[end];
words[end--] = tempc;
}
}
foreach (String s1 in words) {
Console.Write("{0} ",s1);
}
}
}
class reverse {
static void Main() {
string s= "beauty lies in the heart of the peaople";
String[] sent_char=s.Split(' ');
helloworld h1 = new helloworld();
h1.ReverseString(sent_char);
}
}
output:
peaople the of heart the in lies beauty Press any key to continue . . .
Better version
Check my blog http://bamaracoulibaly.blogspot.co.uk/2012/04/19-reverse-order-of-words-in-text.html
public string reverseTheWords(string description)
{
if(!(string.IsNullOrEmpty(description)) && (description.IndexOf(" ") > 1))
{
string[] words= description.Split(' ');
Array.Reverse(words);
foreach (string word in words)
{
string phrase = string.Join(" ", words);
Console.WriteLine(phrase);
}
return phrase;
}
return description;
}
public class manip{
public static char[] rev(char[] a,int left,int right) {
char temp;
for (int i=0;i<(right - left)/2;i++) {
temp = a[i + left];
a[i + left] = a[right -i -1];
a[right -i -1] = temp;
}
return a;
}
public static void main(String[] args) throws IOException {
String s= "i think this works";
char[] str = s.toCharArray();
int i=0;
rev(str,i,s.length());
int j=0;
while(j < str.length) {
if (str[j] != ' ' && j != str.length -1) {
j++;
} else
{
if (j == (str.length -1)) {
j++;
}
rev(str,i,j);
i=j+1;
j=i;
}
}
System.out.println(str);
}
I know there are several correct answers. Here is the one in C that I came up with.
This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.
#include<stdio.h>
char * strRev(char *str, char tok)
{
int len = 0, i;
char *temp = str;
char swap;
while(*temp != tok && *temp != '\0') {
len++; temp++;
}
len--;
for(i = 0; i < len/2; i++) {
swap = str[i];
str[i] = str[len - i];
str[len - i] = swap;
}
// Return pointer to the next token.
return str + len + 1;
}
int main(void)
{
char a[] = "Reverse this string.";
char *temp = a;
if (a == NULL)
return -1;
// Reverse whole string character by character.
strRev(a, '\0');
// Reverse every word in the string again.
while(1) {
temp = strRev(temp, ' ');
if (*temp == '\0')
break;
temp++;
}
printf("Reversed string: %s\n", a);
return 0;
}

Resources