{"id":3411,"date":"2024-05-25T09:54:13","date_gmt":"2024-05-25T13:54:13","guid":{"rendered":"https:\/\/www.yorku.ca\/professor\/drsmith\/?p=3411"},"modified":"2024-05-25T09:54:41","modified_gmt":"2024-05-25T13:54:41","slug":"vpl-testing-arrays-in-java","status":"publish","type":"post","link":"https:\/\/www.yorku.ca\/professor\/drsmith\/2024\/05\/25\/vpl-testing-arrays-in-java\/","title":{"rendered":"VPL: testing arrays in Java with cloning"},"content":{"rendered":"\n<p>On a recent final exam I had students create a method that could interleave two halves of an array.  The original exercise came from a Schaum's Outline book.  If you're not careful, by passing values by reference you can have the student's solution pollute the original input test value.  To solve this in Java you can clone a copy of the test input prior to passing it into the student's method.<\/p>\n\n\n\n<p>The original question is this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">*  Perform a perfect shuffle on an array that is submitted to your method.\n*  This is like a perfect shuffle of a deck of cards.  Interleave the first half of\n*  the array with the second half of the array.  (<a href=\"https:\/\/www.mhprofessional.com\/schaum-s-outline-of-programming-with-java-9780071420402-usa\">Source<\/a>)<\/pre>\n\n\n\n<p>Here is a reference solution<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class TeacherReferenceSolutions {\n\n\n    \/* Method 1 for the Teacher (it's the answer) *\/\n    public  int&#91;]  teacherMethod(int&#91;] originalArray){\/\/, int checkValue) {\n\n        int n = originalArray.length;\n        int m = n\/2;\n        int i = 0;\n        int j = m;\n        int k = 0;\n\n        int&#91;] outputArray = new int&#91;n];\n\n        while(i &lt; m){\n            outputArray&#91;k++] = originalArray&#91;i++];\n            outputArray&#91;k++] = originalArray&#91;j++];\n        }\n\n       \/\/ System.arraycopy(outputArray,0,originalArray,0,k);\n\n        return outputArray;\n        }\n    }<\/code><\/pre>\n\n\n\n<p>Here is the Java jUnit test.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.junit.Assert;\nimport org.junit.Test;\n\nimport javax.swing.*;\nimport java.util.*;\nimport java.util.List;\n\n\npublic class TheTestClass {\n\n\n\n    @Test\n    \/\/ method\n    public void testOne() {\n\n        TeacherReferenceSolutions theReference = new TeacherReferenceSolutions();\n        StudentSolution theStudentAttempt = new StudentSolution();\n        int&#91;] studentAnswer;\n        int&#91;] teacherAnswer;\n\n        final int MIN_INPUT = -10;            \/\/ Boundaries on inputs (max, min)\n        final int MAX_INPUT = +20;\n        final int TEST_TOTALNUMBER = 5;                                                             <span class=\"has-inline-color has-vivid-green-cyan-color\">\/\/ Number of sub-tests run on student vs. teacher.<\/span>\n        final int LENGTH_ROWVECTOR = 10;                                                            <span class=\"has-inline-color has-vivid-green-cyan-color\">\/\/ number of entries in each row vector.<\/span>\n        final int thresholdValue = new Random().nextInt(MAX_INPUT - MIN_INPUT) + MIN_INPUT;  <span class=\"has-inline-color has-vivid-green-cyan-color\">\/\/ this is the max value to be compared against.<\/span>\n        int&#91;] oneRowVector = new int&#91;LENGTH_ROWVECTOR];\n        ArrayList&lt;int&#91;]> allTestArrays = new ArrayList&lt;>();\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/\/ Populate an ArrayList of row vectors.  Each row vector is a new test set.\n<\/span>        for(int i = 0; i &lt; TEST_TOTALNUMBER; i++){\n            for(int j = 0; j &lt; LENGTH_ROWVECTOR; j++){\n                oneRowVector&#91;j] = new Random().nextInt(MAX_INPUT - MIN_INPUT) + MIN_INPUT;\n            }\n            allTestArrays.add(oneRowVector);        \/\/ add one row at a time.\n        }\n\n        <span class=\"has-inline-color has-kb-palette-1-color\">\/\/ Make a copy of the test array and make it immutable. <\/span><span class=\"has-inline-color has-pale-cyan-blue-color\">(doesn't work in current version of JDK with VPL)<\/span><span class=\"has-inline-color has-kb-palette-1-color\">\n        \/\/ https:\/\/docs.oracle.com\/en\/java\/javase\/11\/core\/creating-immutable-lists-sets-and-maps.html#GUID-DB0865D2-C052-40BC-A3DC-20FCB3088DC9\n        \/\/ List&lt;int&#91;]> ALL_TEST_ARRAYS = List.copyOf(allTestArrays);<\/span>\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/* -----------------------------------\n         * First loop.  Print to screen messages that students can more easily decode.\n         * -----------------------------------  *\/<\/span>\n        for (int testIteration = 0; testIteration &lt; TEST_TOTALNUMBER; testIteration++) {\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">            \/\/ extract an integer array for testing (one per row). \n<\/span>            int&#91;] singleRowVectorInput = allTestArrays.get(testIteration);\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">            \/* Run the teacher solution once.  Get the reference output. *\/\n<\/span>            int&#91;] clonedCopyInputForTeacher = singleRowVectorInput.clone();\n            teacherAnswer = theReference.teacherMethod(clonedCopyInputForTeacher);\n            System.out.println(\"Subtest \" + testIteration + \" : testing against inputs : \\t\\t\\t\"\n                    + Arrays.toString(singleRowVectorInput) );\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">            \/\/ Run the student's answer.  Get the student's output. *\/\n<\/span>            int&#91;] clonedCopyInputForStudent = singleRowVectorInput.clone();\n            studentAnswer = theStudentAttempt.studentMethod(clonedCopyInputForStudent);\n\n\n            try {\n                Assert.assertArrayEquals(teacherAnswer, studentAnswer);\n                System.out.println(\"Sub-Test \" + testIteration + \" _passed_. Testing against inputs : \\t\" + Arrays.toString(singleRowVectorInput));\n                System.out.println(\"Teacher solution: \" + Arrays.toString(teacherAnswer) +\n                        \" ... versus student solution: \" + Arrays.toString(studentAnswer));\n                System.out.println(\"------------------------------------------------------\");\n                System.out.println(\"\");\n\n            } catch (AssertionError e) {\n                System.out.println(\"\");\n                System.out.println(\"****************************************************\");\n                System.out.println(\"vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\");\n                System.out.println(\"\\n\\t\\t\\t Sub-Test \" + testIteration + \" + DID NOT PASS!! \\t\\t\\t\\t\");\n                System.out.println(\"For inputs \\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\" + Arrays.toString(singleRowVectorInput));\n                System.out.println(\"Sub-Test \" + testIteration + \" FAILED. Testing against inputs : \\t\" + Arrays.toString(singleRowVectorInput));\n\n                System.out.println(\"We have teacher solution \"  + Arrays.toString(teacherAnswer) +\n                        \" &amp; student output: \" + Arrays.toString(studentAnswer));\n                System.out.println(e.getMessage());\n                System.out.println(\"\");\n                System.out.println(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\");\n                System.out.println(\"****************************************************\");\n                System.out.println(\"\");\n            }\n        }\n\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">        \/* ---------------------------------------------\n         * Second loop.  Allows jUnit to register the error in VPL or in the IDE.\n         * ---------------------------------------------- *\/<\/span>\n        for (int testIteration = 0; testIteration &lt; TEST_TOTALNUMBER; testIteration++) {\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">            \/\/ extract an integer array for testing (one per row). \n<\/span>            int&#91;] singleRowVectorInput = allTestArrays.get(testIteration);\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">            \/* Run the teacher solution once.  Get the reference output. *\/\n<\/span>            int&#91;] clonedCopyInputForTeacher = singleRowVectorInput.clone();\n            teacherAnswer = theReference.teacherMethod(clonedCopyInputForTeacher);\n            System.out.println(\"Subtest \" + testIteration + \" : testing against inputs : \" + Arrays.toString(singleRowVectorInput) );\n           <span class=\"has-inline-color has-vivid-green-cyan-color\"> \/\/ Run the student's answer.  Get the student's output. *\/<\/span>\n            int&#91;] clonedCopyInputForStudent = singleRowVectorInput.clone();\n            studentAnswer = theStudentAttempt.studentMethod(clonedCopyInputForStudent);\n\n<span class=\"has-inline-color has-vivid-green-cyan-color\">            \/\/ no try-catch here.  This will register with the IDE or VPL\n<\/span>            Assert.assertArrayEquals(teacherAnswer, studentAnswer);\n\n\n        }\n\n    }  <span class=\"has-inline-color has-vivid-green-cyan-color\">\/\/ end method<\/span>\n\n\n\n\n}<\/code><\/pre>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignleft size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"128\" height=\"128\" src=\"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-content\/uploads\/sites\/444\/2021\/12\/noun-signature-1720818-2.png\" alt=\"a pen\" class=\"wp-image-2116\"\/><\/figure><\/div>\n\n\n\n<p>James Andrew Smith is a Professional Engineer and Associate Professor in the Electrical Engineering and Computer Science\u00a0<a href=\"http:\/\/eecs.lassonde.yorku.ca\">Department<\/a>\u00a0of York University's\u00a0<a href=\"http:\/\/lassonde.yorku.ca\">Lassonde School<\/a>, with degrees in Electrical and Mechanical Engineering\u00a0from the University of Alberta and McGill University.\u00a0\u00a0Previously a program director in biomedical engineering, his research background spans robotics, locomotion, human birth and\u00a0engineering\u00a0education. While on sabbatical in 2018-19 with his wife and kids he lived in Strasbourg, France and\u00a0he\u00a0taught at the\u00a0<a href=\"https:\/\/www.insa-strasbourg.fr\/en\/\">INSA Strasbourg<\/a>\u00a0and\u00a0<a href=\"https:\/\/www.hs-karlsruhe.de\">Hochschule Karlsruhe<\/a>\u00a0and wrote about his\u00a0<a href=\"https:\/\/twitter.com\/search?q=(%23sabbaticallife)%20(from%3Aonnimikki)&amp;src=typed_query\">personal<\/a>\u00a0and\u00a0<a href=\"https:\/\/twitter.com\/search?q=insa%20(from%3Ajasmith_yorku)&amp;src=typed_query\">professional\u00a0<\/a><a href=\"https:\/\/twitter.com\/search?q=karlsruhe%20(from%3Ajasmith_yorku)&amp;src=typed_query\">perspectives<\/a>.\u00a0\u00a0James is a proponent of using social media to advocate for justice, equity, diversity and inclusion as well as evidence-based applications of research\u00a0in the public sphere.\u00a0You can find him on\u00a0<a href=\"https:\/\/twitter.com\/jasmith_yorku\">Twitter<\/a>. Originally from Qu\u00e9bec City, he now lives in Toronto, Canada.\u00a0\u00a0<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n","protected":false},"excerpt":{"rendered":"<p>On a recent final exam I had students create a method that could interleave two halves of an array. The original exercise came from a Schaum's Outline book. If you're not careful, by passing values by reference you can have the student's solution pollute the original input test value. To solve this in Java you [&hellip;]<\/p>\n","protected":false},"author":762,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_kad_blocks_custom_css":"","_kad_blocks_head_custom_js":"","_kad_blocks_body_custom_js":"","_kad_blocks_footer_custom_js":"","footnotes":""},"categories":[50,294],"tags":[],"class_list":["post-3411","post","type-post","status-publish","format-standard","hentry","category-java","category-vpl"],"taxonomy_info":{"category":[{"value":50,"label":"java"},{"value":294,"label":"VPL"}]},"featured_image_src_large":false,"author_info":{"display_name":"drsmith","author_link":"https:\/\/www.yorku.ca\/professor\/drsmith\/author\/drsmith\/"},"comment_info":"","category_info":[{"term_id":50,"name":"java","slug":"java","term_group":0,"term_taxonomy_id":50,"taxonomy":"category","description":"","parent":0,"count":27,"filter":"raw","cat_ID":50,"category_count":27,"category_description":"","cat_name":"java","category_nicename":"java","category_parent":0},{"term_id":294,"name":"VPL","slug":"vpl","term_group":0,"term_taxonomy_id":294,"taxonomy":"category","description":"","parent":0,"count":25,"filter":"raw","cat_ID":294,"category_count":25,"category_description":"","cat_name":"VPL","category_nicename":"vpl","category_parent":0}],"tag_info":false,"_links":{"self":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts\/3411","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/users\/762"}],"replies":[{"embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/comments?post=3411"}],"version-history":[{"count":2,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts\/3411\/revisions"}],"predecessor-version":[{"id":3413,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/posts\/3411\/revisions\/3413"}],"wp:attachment":[{"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/media?parent=3411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/categories?post=3411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.yorku.ca\/professor\/drsmith\/wp-json\/wp\/v2\/tags?post=3411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}