// a function to compute the position of the first occurrence of NUM in the list
ID: 3594383 • Letter: #
Question
// a function to compute the position of the first occurrence of NUM in the list, // where NUM is passed as a parameter // and positions are counted as an offset from the beginning. if NUM is 5.0 and 5.0 is the FIRST element, the position is // if NUM is 5. and it does not appear, return-1 /I you can write this iteratively or recursively, but you should only have one loop or recursive helper I would expect // [0,1,2,5,5,5,5,5,8,9].positionOfFirstNumFromBeginning(5) 3 // 0,1,3,4,5,5,2,5,8,9] positionofFirstNumFromBeginning (2) 6 public int positionOfFirstNumOccurrence (double num) return StdRandom.uniform (100)//TODO 3: fix thisExplanation / Answer
You have not provided what data type you are using Array or ArrayList. So I am providing solution for both Collection types... Let me know if you still have any issue
For Array
public int positionOfFirstNumOccurance(double num) {
int pos = -1;
for (int i = 0; i < arr.length; i++) {
if(arr[i] == num) {
pos = i;
break;
}
}
return pos;
}
For ArrayList
public int positionOfFirstNumOccurance(double num) {
int pos = -1;
for (int i = 0; i < list.size(); i++) {
if(list.get(i) == num) {
pos = i;
break;
}
}
return pos;
}
Note that in both the cases, ArrayList and Array must be globally declared
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.