id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

gaurav.gupta@mq.edu.au delegation > occursExactlyOnce
prev  |  next  |  chance

Using the two functions that respectively return the first and the last indices of an item in an array (and -1 if the item doesn't exist in the array), define a function that returns true if the passed item occurs exactly once in the array, false otherwise.

int indexOf(int[] data, int item) {
  for(int i=0; i < data.length; i++) {
    if(data[i] == item) {
       return i;
    }
  }
  return -1;
}

int lastIndexOf(int[] data, int item) {
  for(int i=data.length-1; i >= 0; i--) {
    if(data[i] == item) {
       return i;
    }
  }
  return -1;
}

occursExactlyOnce([10, 70, 20, 90], 20) → true
occursExactlyOnce([10, 70, 20, 90], 30) → false
occursExactlyOnce([], 20) → false

...Save, Compile, Run (ctrl-enter)

boolean occursExactlyOnce(int[] data, int item) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 2 Post-solution available

Copyright Nick Parlante 2017 - privacy