Ryan Rampersad's Chronicles
an retired blog of thoughts, opinions, ideas and links
  • About
  • Podcast
  • Links

Archives

Find the Index of Largest Array Element in Java

Finding the index of the largest element in an array is relatively easy. I remember seeing a couple free response questions in the AP Computer Science Exam that involved this type of problem too, so it’s good to know.

You’ll need an array full of numbers, those could be integers, doubles, longs, whatever, as long as it is comprised of a number. My solution uses two data keeping variables, largest and index. The largest variable will keep track of the biggest value in the array while the index variable keeps track of where the largest value was found.

Optionally, I like to set the largest and index variables before I start any testing. largest is set to array[0] and index is set to 0 so that we can skip that initial value.

int[] array = {29, 42, 1, 32, 44, 49, 0, 13, 43, 30};
int largest = array[0], index = 0;
for (int i = 1; i < array.length; i++) {
  if ( array[i] > largest ) {
      largest = array[i];
      index = i;
   }
}

This will set index to 5 because 49 is the largest in the array.

If there had been two instances of 49 in the array, which would have been returned? The first one as the code stands. To change it, one would simply have to change the conditional from greater than to equals or greater than.

int[] array = {29, 42, 1, 32, 44, 49, 0, 13, 43, 49};
int largest = array[0], index = 0;
for (int i = 1; i < array.length; i++) {
  if ( array[i] >= largest ) {
      largest = array[i];
      index = i;
   }
}

This would set index to 9 because 49 is the last largest in the array.

Wouldn’t it be nice of Java had a method that did this for you? Like: Arrays.largest or Arrays.smallest which would work for primitive numeric values. Simple and obvious.

Happy indexing.

PHP Array to String

In Java, you can easily force an array to a string representation. It is invaluable when debugging to able to do this, and while PHP does not provide an obviously named function (or method) for this functionality, it is easy to implement.

You can of course, run off an array with a simple var_dump No big deal there, except you know, formatting and the verbosity of the indents, how many items are in each subarray and on. A more elegant solution is to make a customized function that can imiate the Java method, Arrays.toString(array).

This fulfilled my needs for a quick and easy array to string function.

function array_to_string($array, $options = array()) {
    $options =  array_merge(array(
      "html" => array("open" => "<pre>", "close" => "</pre>"),
      "enclose" => array("open" => "[", "close" => "]"),
      "separator" => ", "
    ), $options);

    $output = $options["html"][0];
    $output = $options["enclose"][0];

    $output = implode($options["separator"], $array);

    $output = $options["enclose"][1];
    $output = $options["html"][1];

    return $output;
}

The function has a few options, it allows you to specify opening and closing tags, defaulting to <pre>, also the opening and closing enclosure symbols, defaulting to square brackets. Finally, the customary glue or separator, commonly a comma. One downside to this method is that it assumes $array is not multidimensional. It would take some iteration or recursion to truly come up with a perfect solution.

PHP & JSON – Fatal error: Cannot use object of type stdClass as array

When working with JSON and PHP, things can get a bit tricky. One such situation might be decoding JSON data, which probably occurs more often than not in a web application.

A view of the fatal error in chrome's resource inspect through an ajax request

Fatal Error ...

I came across this fatal php error:

Fatal error: Cannot use object of type stdClass as array…

The cause was a json_decode call that I thought was entirely innocent.

Apparently, some genious thought it was a great idea to make the return value of the json_decode function be an object. It turns out that you have to explicitly state that you want an array.

$raw = json_decode($json); // bad way
echo( $raw["somekey"] ); // fatal error ...

$better = json_decode($json, true);
echo( $raw["somekey"] ); // no error!

According to the PHP.net documentation on json_decode, you need to set the second assoc argument to true so that PHP will return arrays.

That’s all there is to this silly error.

ArrayList of Objects to Array of Objects

Sometimes you need to use an ArrayList. It can be when you’re lazy or when you want flexibility. Eventually, you’ll want to get away from the ArrayList and use your stores objects as standard object array. Doing this isn’t very complicated but it is slightly hidden.

We’re going to pretend for a moment that we have a class called Card and I’m putting a few cards into an ArrayList. After that, I’ll extract the objects from the ArrayList as a simple array.

ArrayList<Card> cards = new ArrayList<Card>();
cards.add(new Card());
cards.add(new Card());
cards.add(new Card());

// Now to get a standard object array that maintains the object type so there is no need for casting.
Card[] c = cards.toArray( new Card[cards.size] );

The c variable will contain the new standard object array. Java should have a method that does this in a more generic sense.

Final ArrayLists can Change

This wasn’t a revelation or anything. My AP Computer Science class was wondering what would happen if one were to set an ArrayList to final. Remember, when you add the final prefix to an variable declaration, it becomes constant and therefore not changeable. (That definition is where we got lost.)

I wrote some sample code that you can test out on your own. I came to my conclusions based on this same code too.

import java.util.*;
public class FinalArrayList {
	public static void main(String[] args) {
		
		ArrayList<String> list = new ArrayList<String>();
		final ArrayList<String> list2 = new ArrayList<String>();
		
		list.add("hello");
		list.add("world");
		
		list2.add("hello");
		list2.add("world");

		
		for (String item : list) {
			System.out.println("From variable ArrayList - " + item);
		}
		System.out.println("");
		for (String item : list2) {
			System.out.println("From final ArrayList - " + item);
		}
		
	}
}

Definition of Final

I looked up the true definition of final. I came to the same understanding after making my example above. I’ll explain why it makes sense.

A final variable can only be assigned once. This assignment does not grant the variable immutable status. If the variable is a field of a class, it must be assigned in the constructor of its class.

Finally Making Sense

To make sense of this, let’s try another example. Let’s pretend we have the following code.

		final String str = "hello world";
		System.out.println(str.substring(6));

What happens? Did you just say world is printed out? That’s right. However, that is only half the answer. Think about the final String str. Did you catch it yet? A new String object is returned! The original object, the original String is untouched. Strings are immutable as mentioned in the definition above. The final keyword doesn’t affect this property but instead does not let assignments to happen upon the same variable name.

So, to answer my class’ question, “If you make an ArrayList final, can you still add things to it?” Yes you can.

Fixed sample code.

json cookies with PHP

I needed to use a cookie to store a hash string so a user would be remembered the next time they come to visit a site. I was required to store their user id (numeric) and also a secret string that gets hashed. This typically would have required two cookies but I didn’t want two cookies. So I did what any one would do: use json to store my data inside of a cookie.

Little do you know, you can set cookies as arrays but it still causes multiple cookies to be made and sent back and forth between the server and the client. So wrapping my id and hash together in a single cookie saves me time and also saves the user some bandwidth, the bandwidth of only one cookie versus two.

So how did I accomplish putting a json string inside of a cookie? I used PHP5’s json_encode function and of course setcookie. The code is short and simple:

$toCookie = array("id" => 1, "hash"=>"6b585b736c476e772ee8586957c501254a04917b");
$json = json_encode($toCookie);
setcookie("json_cookie", $json);

That was the easy part. Now, how about getting the delicious little guys out? That’s sort of easy, but first, do you know your old friend, get_magic_quotes_gpc, well, if you haven’t met, do it now, because we need his help. A lot of servers have magic quotes turned on, I even had this problem with xampp by default. You have to account for that or your cookie will not be decoded in one piece.

if (get_magic_quotes_gpc() == true) {
 foreach($_COOKIE as $key => $value) {
   $_COOKIE[$key] = stripslashes($value);
  }
}

So now that you’ve cleaned the slashes up, getting the data is easy. Just run json_decode on the cookie. You can decide if you want an object or an array out by passing true as a second argument to get an array.

$cookie = json_decode($_COOKIE["json_cookie"], true);
var_dump($cookie);

Again, it’s not hard and it really does save you from the cookie array syntax mess and also saves the user of having extra cookies.

I hope this helps you to be wise when using cookies.

Randomize an Array with Mootools

Mootools doesn’t offer a native way to randomize an array but it does offer a way to get a single random element from an array.

You can extend Mootools to have an Array.randomize method. It’s really easy to do.

Array.implement({
	randomize: function() {
		return this.sort(function() {return 0.5 - Math.random();});
	}
});

Now you can easily call randomize on an array and you’ll get a random array out of it. I think this should be added to Array.Extras in the Mootools More library.

Random Element from Array in PHP

There is a function called array_rand but it only returns the key for a random element in an array. So here’s a quick function for you that can do it all in just a couple of lines.

	function array_random($array) {
		return $array[array_rand($array)];
	}

Yes, the word array does appear four times, but that isn’t to confuse you but make sure you know it is an array.

© 2021 Ryan Rampersad's Chronicles.