Passing a method with an array parameter to a driver/test file? - java

purpose of this program is to determine whether or not the variable value
is found within any block of an array (the size of this array is specified by
a user.)
All I want to do is call this method in a driver file and have the user input
the size/data in each block of the array and then enter a value that the program will look for in the array.
public class PracticeExamQ10
{
//method that recieves int array and int value//
public int search(int[] data, int value)
{
//for loop to search the entire array for value//
for(int i = 0; i < data.length; i++)
{
//if data is found, return the index number of value (spot in the array)//
if(data[i] == value)
return i;
}
//returns -1 if value does not occur in the array data//
return -1;
}
}
I then have this as my driver file;
public class PracticeExamQ10Test
{
public static void main(String[] args)
{
PracticeExamQ10 test = new PracticeExamQ10();
test.search({5, 4, 3, 2, 1}, 5);
}
}
is this even possible or do I have to do this instead?
public class PracticeExamQ10Test
{
public static void main(String[] args)
{
int[] data = {5, 4, 3, 2, 1};
PracticeExamQ10 test = new PracticeExamQ10();
test.search(data, 0);
}
}

test.search(new int[] { 5, 4, 3, 2, 1 }, 0);

Related

Function in java outputs different results when called multiple times

I have a function called tournamentTreeKSelection which finds the K-th largest element in an array. The function takes three parameters, the array, the same array again and the value of K. The purpose of sending two copies of the array is so that during recursive calls, I can modify one copy of the array and still keep the original array I sent in during that call. Here is the code:
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int[] toArray(ArrayList<Integer> list) {
int[] arr = new int[list.size()];
for(int i = 0; i < arr.length; ++i)
arr[i] = list.get(i);
return arr;
}
public static ArrayList<Integer> toList(int[] arr) {
ArrayList<Integer> list = new ArrayList<>();
for(int i : arr)
list.add(i);
return list;
}
public static int tournamentKSelection(int[] data, int[] data_copy, int k) {
ArrayList<Integer> winners = new ArrayList<>();
for(int i = 0; i < data.length; i += 2) {
winners.add(max(data[i], data[i + 1]));
}
if(k > 1 && winners.size() == 1) {
for(int i = 0; i < data_copy.length; i++)
if(data_copy[i] == winners.get(0))
data_copy[i] = -1;
return tournamentKSelection(data_copy, data_copy, --k);
}
if(winners.size() % 2 == 1 && winners.size() != 1) winners.add(-1);
if(winners.size() == 1) return winners.get(0);
return tournamentKSelection(toArray(winners), data_copy, k);
}
}
Now I am going to test it :
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,1));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,2));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
This produces the following results:
500 // ok this is the first largest number
10 // ok this is the second largest number
8 // this is the fourth largest number, not the third
Now let me make the call to System.out.println(TournamentTree.tournamentKSelection(arr,arr,3)); alone without the call to k = 1 and k = 2
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
Now this produces the correct result, which is 9. What's going on ? Individually, the result is correct but when I make previous calls to the same function first the subsequent results are wrong.
The only explanation I can think of at the moment is that something in my TournamentTree class is static that shouldn't be.
Any insight ?
I think you should call your function in this way:
System.out.println(TournamentTree.tournamentKSelection(arr.clone(), arr.clone(), 1));
And I recommend also interesting thread about arrays and passing them to function:
Are arrays passed by value or passed by reference in Java?
In the call TournamentTree.tournamentKSelection(arr,arr,3), you are passing in the same array for both args, so even though you are not changing the array through the second argument, you are changing it by the first. Java uses pass by reference, not pass by value. To maintain the original, you have to make a copy and pass in each, like:
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
int[] arr_copy = java.util.Arrays.copyOf(arr, arr.length);
System.out.println(TournamentTree.tournamentKSelection(arr,arr_copy,3));
}

two dimensional array with links and linkweights in java

I am working on a page ranking case study where the input is firstly the number of nodes, followed by the links for each page i to page j. The entire input has to be split according to lines and spaces (since the input is one big string consisting of multiple lines with integers). The tests I want to implement are: getNodeSize which simply returns the node, hasLink(integer i, integer j) of boolean whether or not (resp., true or false) there is a link from node i to node j (counting from 0 to nodes-1 ), and a method linkWeight(integer i, integer j) that returns the number of links between integer i and j. (after that there are some other methods but I will figure those out later)
My code so far is:
public class WebGraph {
static Scanner s = new Scanner(System.in);
static int nodes = s.nextInt();
double wg [][]= new double [nodes][nodes];
static ArrayList<String> array = new ArrayList<String>();
static int[][] counts = new int[nodes][nodes];
static int[] outDegree = new int[nodes];
public static WebGraph initFromScanner(Scanner s) {
do{
for(int i = 0; i<nodes-1; i++){
}
String[] strArray = s.nextLine().split("\\s+");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
}while(s.hasNext());
return null;
}
public Object getNodeSize() {
nodes = s.nextInt();
return nodes;
}
public boolean hasLink(int i, int j) {
for (int h = 0; h<wg[i].length; h++) {
if(h==j){
return true;
}
}
return false;
}
public void linkWeight(int a, int b) {
while (s.hasNext()) {
int i = s.nextInt();
int j = s.nextInt();
outDegree[i]++;
counts[i][j]++;
}
}
public List<Integer> successorsSortedList(int i) {
// TODO Auto-generated method stub
return null;
}
public int[][] asMatrix() {
return null;
}
public Set<Integer> successorsSortedSet(int i) {
return null;
}
}
for the testcase:
public class I5Exc4aTest {
WebGraph wg;
/**
* This will be invoked before each testcase.
* Ensure to copy/paste the content of file
* 'ext/web1.txt' to the Eclipse console.
* In L6, we will teach you how to automate that!
* #throws Exception
*/
#Before
public void setUp() throws Exception {
Scanner s = new Scanner(System.in);
System.out.println("Please copy/paste the content of "
+ "file 'ext/web1.txt' to this console. "
+ "Then, press ENTER.");
wg = WebGraph.initFromScanner(s);
}
#Test
public void testGetNodeSize() {
assertEquals(50, wg.getNodeSize());
}
#Test
public void testHasLink1() {
assertFalse(wg.hasLink(0, 0));
}
#Test
public void testHasLink2() {
assertTrue(wg.hasLink(0, 7));
}
#Test
public void testLinkWeight1() {
assertEquals(1, wg.linkWeight(0, 7));
}
#Test
public void testLinkWeight2() {
assertEquals(1, wg.linkWeight(0, 34));
}
#Test
public void testLinkWeight3() {
assertEquals(2, wg.linkWeight(1, 22));
}
#Test
public void testSuccessorsSortedList() {
List<Integer> a = wg.successorsSortedList(1);
List<Integer> expected = Arrays.asList(new Integer(14),
new Integer(22), new Integer(22), new Integer(45));
assertTrue("Expected 'a' and 'expected' to be equal."+
"\n 'a' = "+a+
"\n 'expected' = "+expected,
expected.equals(a));
}
#Test
public void testSuccessorsSortedSet() {
Set<Integer> a = wg.successorsSortedSet(1);
Set<Integer> expected = new java.util.TreeSet<Integer>(
Arrays.asList(new Integer(14), new Integer(22), new Integer(45)));
assertTrue("Expected 'a' and 'expected' to be equal."+
"\n 'a' = "+a+
"\n 'expected' = "+expected,
expected.equals(a));
}
#Test
public void testAsMatrix1() {
int[][] copy= wg.asMatrix();
assertArrayEquals(new int[]{0, 1, 0, 1, 0, 0}, copy[0]);
assertArrayEquals(new int[]{1, 0, 1, 0, 0, 1}, copy[1]);
assertArrayEquals(new int[]{0, 1, 2, 0, 1, 0}, copy[2]);
assertArrayEquals(new int[]{1, 2, 0, 1, 0, 0}, copy[3]);
assertArrayEquals(new int[]{1, 1, 0, 0, 0, 1}, copy[4]);
assertArrayEquals(new int[]{0, 1, 0, 2, 0, 0}, copy[5]);
}
}
Any help on any of the methods would be greatly appreciated since now none of my test cases work.
EDIT:
I am sorry for the unclear parts, this is the complete assignment:
"1.Provide a class WebGraph with an attribute w, and a method initFromScanner(Scanner s) that initializes itself by reading from the command line, based on the following format:
(a) The first input value is of type integer and represents the number of
nodes in the graph. In the following, we call the value of that integer N,
(b) The next N lines always start by an integer i representing a source
node's ID and then a (potentially empty) sequence of integers j that
denote links from node i to node j.
An example corresponding to this structure is listed below. This
example encompasses 5 nodes, where there a link from node 0 to
node 1, a link from node 0 to node 2, but no link from node 0 to
itself nor to nodes 3 or 4.
5
0 1 2
1 1 2 3
2 2 2 2 3 1
3
4 3 0 0
Provide a method getNodeSize that returns the value of N,
Provide a method hasLink(integer i, integer j) of type boolean
that returns whether or not (resp., true or false) there is a link from
node i to node j (counting from 0 to N-1 ),
Provide a method linkWeight(integer i, integer j) of type integer
that returns the number of links from node i to node j (counting from 0
to N-1 ),
Provide a method successorsSortedSet(integer i) of type Set
which represents the set of successor nodes according to the outgoing links
of node i, ordered by node ID.
Provide a method successorsSortedList(integer i) of type List
which represents a sequence of successor nodes according to the outgoing
links of node i, ordered by node ID.
Provide a method asMatrix() of type integer[][] that returns the ma-
trix representation described above. Ensure that you do not allow updates to the internal data of your object!"

Java - Recursive Method that takes Cumulative sum in one array and returns another

So here is the problem: create a int [] recursive method that computes cumulative sums in the array numbers, and transform each value in the array by adding to the value the sum of values that precede it in the array. For example, if
numbers = [5, 6, 7, 2, 3, 1],
then
result = [5, (5)+6, (5+6)+7, (5+6+7)+2, (5+6+7+2)+3, (5+6+7+2+3)+1],
i.e.,result = [5, 11, 18, 20, 23, 24].
The caveats are: Cannot use static or void methods, cannot use loops.
Here is my code so far:
public int[] computeCumulativeSums(int[] numbers){
if(numbers.length == 0)
{
return numbers; // Base case
}
else
{
//recursive stage not implemented. Don't know how to implement
return numbers;
}
}
//Helper method
public int [] addNumbers(int [] list, int index)
{
if(index == 0)
{
return list; //Helper method base case
}
else
{
//recursive case
return addNumbers(list, index - 1);
}
}
public boolean searchTable(int[][] data, int element){
return true;
}
public static void main(String [] args){
Recursion r = new Recursion();
int[] numbers = new int[] {5, 6, 7, 2, 3, 1};
System.out.println(Arrays.toString(r.computeCumulativeSums(numbers)));
}
Output: [5, 6, 7, 2, 3, 1]
What I'm asking is a push in the right direction because I'm so lost with this. Your help will be much appreaciated.
What I would recommend is: try to do it with a while loop. The conditions. In the while loop is your stop condition. Now try to convert what is in the while loop into a recursive method (or if you can't, just a method, and then see how the each method could do the following call of the method itself). Does it help you?
State your strategy .. then code the recursive function. You would probably have something like:
function summit(array, i) ...
if i > 0, then set array[i]=array[i-1]+array[i]
if i < array.length the call summit(array,i+1)
return
public static void main(String args [])
{
int [] array = {5,6,7,2,3,1};
array = sum(array,0);
for(int i=0; i<array.length; i++){
System.out.print(" "+array[i]);
}
}
public static int[] sum(int[] array, int index){
if(index==array.length){
return array;
}
if(index!=0){
array[index] += array[index-1];
}
return sum(array,index+1);
}
Output: 5 11 18 20 23 24

How do I get the index of an array which I don't know?

The Task
Method:
public int indexOfTarget (int[] values, int target)
Description:
Compulsory Exercise 8) Complete the indexOfTarget method which is passed two parameters: an array of ints(values) and an int(target). The method returns the index position within the array of the first occurrence of the specified integer target. If target occurs in the array, then the index of the first such occurrence is returned.
For example, if the input array is
{3, 7, 2, 4} and the target is 7
the method returns 1
If no such integer occurs in this array, then -1 is returned.
An example:
indexOfTarget({3, 7, 2, 4}, 7)` should return 1.
So Far I Have Written:
public int indexOfTarget (int[] values, int target) {
int targetMatch=-1;
for(int i=0;i<values.length;i++){
if(values[i]==target){
targetMatch=values[i];
}
}
return targetMatch;
}
The Results of CodeWrite Errors
(source: gyazo.com)
you should have targetMatch = i instead. You want the index value, not the value of the array at that index.
You want targetMatch = i; not targetMatch=values[i];
You should be saving the index, not the value.
I would also add break; inside the if statement, immediately after you set the value of targetMatch
This java code should work for all scenarios when the array contains a valid int value. * is not a valid int value.
public class Program
{
public static void main(String[] args)
{
int[] values= {3, 7, 2, 4};
int target = 7;
int position = indexOfTarget(values,target);
if(position>-1)
System.out.println("Pass");
else
System.out.println("Fail");
}
public static int indexOfTarget (int[] values, int target) {
int targetMatch=-1;
for(int i=0;i<values.length;i++){
if(values[i]==target){
targetMatch=i;
return i;
}
}
return targetMatch;
}
}

Modifying Array Size Via Static Method

I am trying to resize an array by adding the array size by 1 per method invoke.
I have created a static method and it takes array as its argument.
public static void addArray(int arrayName[]) {
int tempNum[] = new int[arrayName.length]; // save the numbers before add array size
for (int i = 0; i < arrayName.length; i++) { // because by adding/removing array size, it would clear element array
tempNum[i] = arrayName[i];
}
arrayName = new int[arrayName.length + 1]; // adds array size by 1
for (int i = 0; i < arrayName.length - 1; i++) { // sets all the saved numbers to the new element in the array
arrayName[i] = tempNum[i]; // stops at (length - 1) because I want to leave it blank at the last element
}
}
(sorry if the code is messed up, I don't know how to properly post code in here)
In the main, I do this;
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
addArray(num);
System.out.println(num.length);
}
As you can see, the default array size (length) should be 5, but no matter how many times I invoke the method, it always print as 5.
Now I'm starting to think that static method does not allow the array from main to be resized ?
If it can't, do you have another way to resize an array by specifically using static method only ?
You need to return the array from the function:
public static int[] addArray(int arrayName[]) {
...
arrayName = new int[arrayName.length + 1]; // adds array size by 1
...
return arrayName;
}
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
num = addArray(num);
System.out.println(num.length);
}
You can simply do this:
int num[] = {0, 1, 2, 3, 4};
num = Arrays.copyOf(num, num.length + 1);
System.out.println(num.length);
This should then print 6.
The issue with your code is that when you call a method, the method receives a copy of the reference. Thus, the method cannot change what object is referenced by the variable in the calling method.
Another approach is to make num a static field::
static int num[] = {0, 1, 2, 3, 4};
public static void main(String[] args) {
addArray(); // or use Arrays.copyOf() as above
System.out.println(num.length);
}
public static void addArray() {
int tempNum[] = new int[num.length + 1];
System.arraycopy(num, 0, tempNum, 0, num.length);
num = tempNum;
}
What you can't do (without complex reflection code) is pass a variable name to the method and have it change the length of an array with that name.

Categories