array in reverse order

Hi,

I am working on below challenge
http://codingbat.com/prob/p112409

public int[] reverse3(int[] nums) {

  if(nums.length>=3){
  
  // (1) create a java int array
int[] numsReverse= new int[3];
 
// (2) some time later ... assign elements to the array in reverse order
numsReverse[0] = nums[2];
numsReverse[1] = nums[1];
numsReverse[2] = nums[0];
  
  return numsReverse;
  }
  
  else
  return null;
}

Open in new window


i wrote as above and passed all tests. I wonder how i can improve above code or any alternate ways to do it. please advise
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
return new int[]{nums[2],nums[1],nums[0]};
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gurpsbassiCommented:
Try this:

public static int[] reverseNumericOrder(final int[] inputData){

        final int[] newData = Arrays.copyOf(inputData, inputData.length);

        for (int i = 0; i < newData.length / 2; i++) {
            final int temp = newData[i];
            newData[i] = newData[newData.length - 1 - i];
            newData[newData.length - 1 - i] = temp;
            }

        return newData;
        }

    }

Open in new window


The code operates on both ends of the array. It is optimized to only work up to the middle element otherwise you will end up swapping the same element twice.
0
krakatoaCommented:
Another way :

public int[] reverse3(int[] nums) {


int[] newNums = new int[nums.length];

  for(int r=nums.length-1;r>-1;r--){
  
       newNums[r] = nums[nums.length-1-r];
  
  }
  
  
  return newNums;
}

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

awking00Commented:
And another -
public int[] reverse3(int[] nums) {
  int num1 = nums[0];
  nums[0] = nums[2];
  nums[2] = num1;

return nums;
}
0
krakatoaCommented:
Nah . . . this is much better;  Far more efficient :

public int[] reverse3(int[] nums) {
  
  
  StringBuilder revnumst = (new StringBuilder(Arrays.toString(nums))).reverse();
  
  String revnums = revnumst.toString().replace("]","");
  revnums = revnums.replace("[","");
  revnums = revnums.replace(",","");
 
  String[] srevs =  revnums.split(" ");
  
  for (int y=0;y<srevs.length;y++){
  nums[y]=Integer.parseInt(srevs[y]);}

  return nums;

}

Open in new window

0
CEHJCommented:
I wonder how i can improve above code
You can get rid of the length check - the length is given. Otherwise it's already as efficient as it can get
0
krakatoaCommented:
Just FOI, this takes about 26 seconds to reverse aroud 8.3 million ints -

import java.util.*;

class Reversal{

public static void main(String[] args){

System.out.println(Integer.MAX_VALUE/256);

long starttime = System.currentTimeMillis();

int[] nums=new int[Integer.MAX_VALUE/256];

for(int a=0;a<Integer.MAX_VALUE/256;a++){
	nums[a]=a+1;
}
 
  StringBuilder revnumst = (new StringBuilder(Arrays.toString(nums)));
  
  String revnums = revnumst.toString().replace("]","");
  
  revnums = revnums.replace("[","");
 
  String[] srevs =  revnums.split(",");
  
  String[] reversednums = new String[srevs.length];
  
  for(int y=0;y<reversednums.length;y++){reversednums[y] = srevs[srevs.length-1-y];}
  
  for (int y=0;y<reversednums.length;y++){
  nums[y]=Integer.parseInt(reversednums[y].trim());}
  
  //for(int a=0;a<nums.length;a++){System.out.println(nums[a]);}
  
long endtime = System.currentTimeMillis();

System.out.println(endtime-starttime);

}



}

Open in new window


(Couldnt  be bothered to change the JVM heap size)

. . .  btw awking00 - I was of course joking. ;)
0
gurpsbassiCommented:
mine runs faster using the same dataset as Krakatoa (8.3 million ints).
It's the classic solution for the reversal problem in computer science.
0
krakatoaCommented:
mine runs faster

. . .  I should hope so! My string code was an exercise in otherness.

But now you've told us it's faster, are you going to add to the collective nouse and tell us by how much ?
0
krakatoaCommented:
>>Mine runs faster<<

From my tests, the array copying code I posted earlier runs in this timeframe :

C:\EE_Q_CODE>java IntReverser
2097151
63

namely 63 millis, and your code runs :

C:\EE_Q_CODE>java gurpsIR
2097151
78

i.e. in 78 millis.


* In fact you can halve the time my code takes, since the stopwatch originally included making the array from scratch in the first place. So the real figure for the millis is around 31.

Thus my class code ends up as -

class IntReverser{

  public static void main(String[] args){

   //long starttime = System.currentTimeMillis();

   System.out.println(Integer.MAX_VALUE/1024);

   int[] nums=new int[Integer.MAX_VALUE/1024];//1024

   for(int a=0;a<Integer.MAX_VALUE/1024;a++){//1024
	   nums[a]=a+1;
   }
   
   long starttime = System.currentTimeMillis(); // this is the right place to start the clock.

   int[] newNums = new int[nums.length];

   for(int r=nums.length-1;r>-1;r--){
  
       newNums[r] = nums[nums.length-1-r];
  
  }
  
    //return newNums;
	
  long endtime = System.currentTimeMillis();

  System.out.println(endtime-starttime);
  System.out.println("First array position: "+newNums[0]+" ...last array position : "+newNums[newNums.length-1]);
  
  
  }
  }

Open in new window

0
ozoCommented:
Given an array of ints length 3, as per the requirements specification: http://codingbat.com/prob/p112409
the code in http:#a40829730 runs about twice as fast as the code in http:#a40829846 but still not as fast as the code in http:#a40830424
0
krakatoaCommented:
Well it would, wouldn't it, given such a small array. My point was that for large arrays where you dont want to tight bind the values nor type in all those assignments.
Codingbat isnt really dealing with more than just basic notions.
0
CEHJCommented:
    public static int[] reverseNumericOrder(final int[] inputData) {
        final int[] newData = new int[inputData.length];

	int newIx = 0;
        for (int i = newData.length;--i>=0;) {
            inputData[i] = newData[newIx++];
        }

        return newData;
    }

Open in new window

should run faster
0
ozoCommented:
Codingbat isnt really dealing with more than just basic notions.
which we should be addressing in our answers.
http:#a40830518 only passes the tests because the only two digit number tested happens to be a palindrome.
And even though its the slowest of the above methods, you still have to go through extremes to make the time noticeable.
One would have to reverse a lot of array of ints length 3 to use up as many computer cycles as we have just sending these comments back and forth.
0
ozoCommented:
inputData[i] = newData[newIx++];

Open in new window

I think you meant
newData[i] = inputData[newIx++];

Open in new window

0
krakatoaCommented:
Sorry, I don't follow you about palindromes - the code I posted works on Codingbat, but it also works for 8.3 M ints in a standalone class, where numbers like 97 are afaik not palindromes.
0
krakatoaCommented:
@CEHJ -

Your code seems to run in the same time as mine, but the first and last elements of the new array are both "0", so I'm not sure what's going on there.
0
ozoCommented:
Ok, given that "works" is not clearly defined for anything other than the examples tested by http://codingbat.com/prob/p112409 I'll accept that it is possible to define a requirements specification for which http:#a40830518 works :-)
0
krakatoaCommented:
Yeah, that was an assignment error. Now it runs.

My timings for it and my code are :

C:\EE_Q_CODE>java CEHJRev
31
First array position: 2097151 ...last array position : 1

C:\EE_Q_CODE>java IntReverser
2097151
15
First array position: 2097151 ...last array position : 1
0
krakatoaCommented:
ID: 40831970

I'm not in competition with you here . . . I am simply providing other comparative perspectives on how code of various complexions is more or less suitable or productive than other code - beyond the Codingbat briefs, which should usually have been dealt with already.
0
CEHJCommented:
I think you meant

Oops! ;)
0
krakatoaCommented:
@CEHJ -

I think your loop will be slower than mine, as you are making  an increment and a decrement, whereas mine only a decrement.
0
CEHJCommented:
Any code that's in the test harness needs to be posted, along with the harness
0
ozoCommented:
not in competition with you
if it's a competition for speed, the >>Mine runs faster<< exchange seems to have been between gurpsbassi and krakatoa, although awking00 would be in the lead.

If it's a competition about ways to interpret "elements in reverse order",
there have been two different interpretations for what one should get for
reverse3({97, 970, 9700}) ->

http:#a40829784 might win on originality, but the majority interpretation has the possibly useful property that reverse3(reverse3(num)) gets you back to the original.
0
krakatoaCommented:
[...] test harness

Here is my code:

class IntReverser{

  public static void main(String[] args){

   //long starttime = System.currentTimeMillis();

   System.out.println(Integer.MAX_VALUE/1024);

   int[] nums=new int[Integer.MAX_VALUE/1024];//1024

   for(int a=0;a<Integer.MAX_VALUE/1024;a++){//1024
	   nums[a]=a+1;
   }
   
   long starttime = System.currentTimeMillis(); // this is the right place to start the clock.

   int[] newNums = new int[nums.length];

   for(int r=nums.length-1;r>-1;r--){
  
       newNums[r] = nums[nums.length-1-r];
  
  }
  
    //return newNums;
	
  long endtime = System.currentTimeMillis();

  System.out.println(endtime-starttime);
  System.out.println("First array position: "+newNums[0]+" ...last array position : "+newNums[newNums.length-1]);
  
  
  }
  }

Open in new window


and here is yours ( I just substitued "nums" for your original name, which won't make any difference of course). :

class CEHJRev {


public static void main(String[] rgs){

//public static int[] reverseNumericOrder(final int[] inputData) {
int[] nums=new int[Integer.MAX_VALUE/1024];//1024

   for(int a=0;a<Integer.MAX_VALUE/1024;a++){//1024
	   nums[a]=a+1;
   }
   
   long starttime = System.currentTimeMillis(); // this is the right place to start the clock.
        final int[] newData = new int[nums.length];

	int newIx = 0;
        for (int i = newData.length;--i>=0;) {
            newData[i] = nums[newIx++];
        }

        //return newData;
    //}
	
	
	long endtime = System.currentTimeMillis();

  System.out.println(endtime-starttime);
  System.out.println("First array position: "+newData[0]+" ...last array position : "+newData[newData.length-1]);

   

   


}


}

Open in new window

0
krakatoaCommented:
@ozo

the code in http:#a40829730 runs about twice as fast as the code in http:#a40829846 but still not as fast as the code in http:#a40830424

et tu brute. :)

You were wrong in thinking that my string code reversed the digits in the ints - it doesn't - it reverses the string of ints. ;)

but the majority interpretation has the possibly useful property that reverse3(reverse3(num)) gets you back to the original.
I didn't suffer from that belief personally. Codingbat asked for it to be reversed once, and not to regain the original.
0
CEHJCommented:
I think your loop will be slower than mine, as you are making  an increment and a decrement, whereas mine only a decrement.
That's interesting. I first thought of doing it the same way as you but thought that the calculation might be slower - i was wrong ;)
0
krakatoaCommented:
Well, as befits your standing on this site, you are ever gracious in your comments. ;)

But the news in fact is that running the two against each other and taking the averages of 8 thousand million reversals, your code appears to be between 1 and 2 milliseconds faster than mine.

Your code ran first 1000 times, and came in at 6 Ms. Mine at 7 Ms. Reversing the order of the 1000 calls led mine to come in at an average of 8, and yours at between 5 and 6.

I wouldn't call my test Computer-Science-scientific, but it would appear that yours does the trick, with the margin closing in sometimes on 40% faster. I wish I could understand that. ;)

(especially as it appears to make no sense when held against the individual run results).
0
ozoCommented:
I didn't suffer from that belief personally
What belief is that? The belief that the majority interpretation has that property?
The belief that the property is possibly useful?  The belief (which statement you quote does not express) that the requirements specification for reverse3 demands that property?
I already conceded that it is possible to define a requirements specification for which http:#a40830518 works,
but I will here state the belief that it does not seem unreasonable to to expect an operation referred to as "reverse" to be an involution, that is, to be its own inverse.
As evidence, the majority of the above reverse3 functions are involutions.
Some of those functions only have the property of being an involution for an array of ints length 3, but that was given to be the domain of the function.   On the other hand, palindromic numbers was not a declared de jure domain, although it was a de facto domain of the tests.
0
krakatoaCommented:
No idea what point you are trying to make there. But  let's not cause the Internet to freeze up over this.
0
krakatoaCommented:
gudii9:

. . . how i can improve above code . . .

One way would be to realise that if you had to deal with an array which was larger than the trivial size of the one in this challenge, that coding it like this :

// (2) some time later ... assign elements to the array in reverse order
numsReverse[0] = nums[2];
numsReverse[1] = nums[1];
numsReverse[2] = nums[0];

would be a complete nonsense. How long would it take you to (re-)assign those indexes if you had 1000 of them? 10,000 of them? 10,000,000? Try it.
0
ozoCommented:
string code reversed the digits in the ints - it doesn't
the string code in http:#a40832054 doesn't.
But then, it doesn't reverse the ints either, all it does is establish the length of the arrays used in the following for loops which actually do the reversal (and suffer the belief that a reversal is an involution)
0
ozoCommented:
No idea what point you are trying to make
the point that the code in http:#a40830518, which
was of course joking
was joking in more than one way, in that it implements an unusual interpretation of "elements in reverse order"
0
krakatoaCommented:
http:#a40832054 doesn't.
Eh??
0
ozoCommented:
http:#a40832054 doesn't reverse the digits in the ints

http:#a40830518 on the other hand...
0
krakatoaCommented:
http:#a40832054 doesn't reverse the digits in the ints

Is that one of *my* comments?
0
ozoCommented:
your comment in http:#a40832007, quoted in http:#a40832171, was
string code reversed the digits in the ints - it doesn't
which is a true statement if applied to http:#a40830757 (I'm not sure how "http:#a40830757" morphed into "http:#a40832054")
0
krakatoaCommented:
You morphed it, not me. I've never quoted those comments for their code content. I quoted them to you due to the referral to "competition".

I've only ever been referring to http://www.experts-exchange.com/questions/28689460/array-in-reverse-order.html#a40830757 as code which *does* reverse the array contents.
0
krakatoaCommented:
Thus now you recognise that my string code does reverse the array contents, I have no idea what you objected to in http://www.experts-exchange.com/questions/28689460/array-in-reverse-order.html#a40832184

because it might be "unusual", but that doesnt mean it doesnt work.
0
ozoCommented:
I've never disagreed that about http://www.experts-exchange.com/questions/28689460/array-in-reverse-order.html#a40830757, nor tried to reference it before attempting to make a true statement out of
string code reversed the digits in the ints - it doesn't
0
krakatoaCommented:
OK, once more: you said this :

"only passes the tests because the only two digit number tested happens to be a palindrome."

*You*mentioned digits, not me.

My string-based code snippet deals with the array contents (array indexed ints) not the digits of those ints, that's the point. My code reverses the order of the ints in the original array.
0
ozoCommented:
The definition of "work" required to make it a description of http://#a40830518 seemed sufficiently unusual to point out that it might not conform to the definition of "work" that one might be using to describe most of the other routines here, (assuming one considers them to "work")
0
krakatoaCommented:
Yes . . . and it was precisely for that reason that I (now regrettably) introduced the comment about it being a  'joke' to awking00.

Obviously it is going to be expensive and clumsy to do it that way; but my point was that it *did* pass the test, that it *is not* hard-wired to the size of the array, and that it simply shows what byzantine lengths you can go to to get something done.
0
ozoCommented:
Expensive and clumsy is not an issue here (unless one is in a competition)
A hard-wired size of the array is part of the problem specification.
But passing only tests in which all the integers happen to be palindromes seemed unusual enough to be noteworthy.
0
krakatoaCommented:
Expensive and clumsy is not an issue (unless one is in a competition) 

Open in new window


I think it might be almost time to ask a Mod as to whether you are being deliberately controversial here (not to mention previously). An IMPORTANT point in any code is that it should not be knowingly profligate - I don't see why you even need to make the comment that it is not an issue. I'm taken aback quite honestly.

But as for you fixation about palindromes, perhaps you can explain where they come in?
0
ozoCommented:
I hadn't thought of my code as being "knowingly profligate".

As for palindromes, have you tried running http:#a40830518, even as a joke, on arrays containing numbers that aren't decimal palindromes?
0
krakatoaCommented:
Alright - I give in . . . what is a 'decimal palindrome' ?
0
ozoCommented:
https://en.wikipedia.org/?title=Palindromic_number
You might observe that all the numbers used in the tests on http://codingbat.com/prob/p112409 happen to be in this list http://oeis.org/A002113
0
krakatoaCommented:
Right . . . ok . . . with you so far on all the above.

And your point is  ?
0
krakatoaCommented:
Here is *some* of the output of the string code (printed every 10000%12, actually, just to see *some* results, without waiting to print the entire array).

C:\EE_Q_CODE>java Reversal
2097151
2097139
2087139
2077139
2067139
2057139
2047139
2037139
2027139
2017139
2007139
1997139
1987139
1977139
1967139
1957139
1947139
1937139
1927139
1917139
1907139
1897139
1887139
1877139
1867139
1857139
1847139
1837139
1827139
1817139
1807139
1797139
1787139
1777139
1767139
1757139
1747139
1737139
1727139
1717139
1707139
1697139
1687139
1677139
1667139
1657139
1647139
1637139
1627139
1617139
1607139
1597139
1587139
1577139
1567139
1557139
1547139
1537139
1527139
1517139
1507139
1497139
1487139
1477139
1467139
1457139
1447139
1437139
1427139
1417139
1407139
1397139
1387139
1377139
1367139
1357139
1347139
1337139
1327139
1317139
1307139
1297139
1287139
1277139
1267139
1257139
1247139
1237139
1227139
1217139
1207139
1197139
1187139
1177139
1167139
1157139
1147139
1137139
1127139
1117139
1107139
1097139
1087139
1077139
1067139
1057139
1047139
1037139
1027139
1017139
1007139
997139
987139
977139
967139
957139
947139
937139
927139
917139
907139
897139
887139
877139
867139
857139
847139
837139
827139
817139
807139
797139
787139
777139
767139
757139
747139
737139
727139
717139
707139
697139
687139
677139
667139
657139
647139
637139
627139
617139
607139
597139
587139
577139
567139
557139
547139
537139
527139
517139
507139
497139
487139
477139
467139
457139
447139
437139
427139
417139
407139
397139
387139
377139
367139
357139
347139
337139
327139
317139
307139
297139
287139
277139
267139
257139
247139
237139
227139
217139
207139
197139
187139
177139
167139
157139
147139
137139
127139
117139
107139
97139
87139
77139
67139
57139
47139
37139
27139
17139
7139
6066

Do they all look like palindromes to you ?
0
ozoCommented:
10000%12 == 4, so I'm not sure what you are printing
and http:#a40830518 has no print statements, so I'm not sure what you are using for a test harness
0
krakatoaCommented:
10000%12 was just some pair of numbers "pick any number" - it doesnt matter. It was just to cut down the tedium of the entire output. I already said that - explained that. And it's a detail; not relevant to the discussion particularly.

#a40830518 has no print statements because it's the Codingbat schema - my offline code uses 30518's guts, that's the point. As for what is printed - that was the long list in my last comment obviously.

But if you want the code, here it is:

import java.util.*;

class Reversal{

public static void main(String[] args){


long starttime = System.currentTimeMillis();

System.out.println(Integer.MAX_VALUE/1024);

int[] nums=new int[Integer.MAX_VALUE/1024];

for(int a=0;a<Integer.MAX_VALUE/1024;a++){
	nums[a]=a+1;
}
 
  StringBuilder revnumst = (new StringBuilder(Arrays.toString(nums)));
  
  String revnums = revnumst.toString().replace("]","");
  
  revnums = revnums.replace("[","");
 
  String[] srevs =  revnums.split(",");
  
  String[] reversednums = new String[srevs.length];
  
  for(int y=0;y<reversednums.length;y++){reversednums[y] = srevs[srevs.length-1-y];}
  
  for (int y=0;y<reversednums.length;y++){
  nums[y]=Integer.parseInt(reversednums[y].trim());}
  
  for(int a=0;a<nums.length;a++){if(a%10000==12){System.out.println(nums[a]);}}
  
long endtime = System.currentTimeMillis();

System.out.println(endtime-starttime);

}



}

Open in new window


(starttime is not in the correct place here - it includes the establishment of an array of ints to work on). But that doesnt matter either - everyone knows, including me, that this is a non-starter for real deployment.
0
ozoCommented:
That's the code from http:#a40830757
I was talking about the code from http:#a40830518
Since I have had some problems with references earlier, I'll quote it to avoid confusion:
public int[] reverse3(int[] nums) {
  
  
  StringBuilder revnumst = (new StringBuilder(Arrays.toString(nums))).reverse();
  
  String revnums = revnumst.toString().replace("]","");
  revnums = revnums.replace("[","");
  revnums = revnums.replace(",","");
 
  String[] srevs =  revnums.split(" ");
  
  for (int y=0;y<srevs.length;y++){
  nums[y]=Integer.parseInt(srevs[y]);}

  return nums;

}

Open in new window

0
krakatoaCommented:
I don't know what you are trying to get at. You have all the comments and the code, same as I do. You can try what "works", as you insist on qualifying every piece of code by, and what then "doesn't". AFAIK all the code I posted on this thread works - the Codingbat code works in Codingbat, and the other code "works" in the JVM. You'll have to figure the rest out for yourself I'm afraid - I'm out.
0
ozoCommented:
Do you see the difference between
18:  StringBuilder revnumst = (new StringBuilder(Arrays.toString(nums)));
and
4:  StringBuilder revnumst = (new StringBuilder(Arrays.toString(nums))).reverse();
?

Do you see the difference between
24:  String[] srevs =  revnums.split(",");
25:
26:  String[] reversednums = new String[srevs.length];
27:
28:  for(int y=0;y<reversednums.length;y++){reversednums[y] = srevs[srevs.length-1-y];}
29:
30:   for (int y=0;y<reversednums.length;y++){
and
10:  String[] srevs =  revnums.split(" ");
11:
12:  for (int y=0;y<srevs.length;y++){
?

Do you see why one might behave differently than the other?
Do you see under what limited circumstances they may appear to behave similarly?
0
krakatoaCommented:
Yes, and I had completely forgotten that I revised the code to handle that eventuality offline, and I should have mentioned that somewhere in a post between the two lots of code.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.