target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayPage(SPANNER_ID); assertNotNull("no response", response); assertEquals("view", VIEW_EDIT_SPANNER, response.getViewName()); SpannerForm spannerFormData = (SpannerForm)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerFormData); } | @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); static final String VIEW_EDIT_SPANNER; static final String VIEW_UPDATE_SUCCESS; static final String VIEW_VALIDATION_ERRORS; static final String MODEL_SPANNER; static final String CONTROLLER_URL; } |
@Test public void testUpdateUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.updateUser(user); server.verify(); } | @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } | RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } } | RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); } | RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } | RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } |
@Test public void testSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayPage(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } } | @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); } | EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); static final String VIEW_EDIT_SPANNER; static final String VIEW_UPDATE_SUCCESS; static final String VIEW_VALIDATION_ERRORS; static final String MODEL_SPANNER; static final String CONTROLLER_URL; } |
@Test public void testDeleteUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.OK)); service.deleteUser(USERNAME); server.verify(); } | @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } | RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } } | RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); } | RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } | RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } |
@Test public void testUserExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); boolean userExists = service.userExists(USERNAME); assertTrue(userExists); } | @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } |
@Test public void testUserNotExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withStatus(HttpStatus.NOT_FOUND)); boolean userExists = service.userExists(USERNAME); assertFalse(userExists); } | @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } | RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } |
@Test public void changePassword() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PATCH)) .andRespond(withStatus(HttpStatus.OK)); service.changePassword(USERNAME, PASSWORD); server.verify(); } | @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } | RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } } | RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); } | RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } | RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); } |
@Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); } | public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } | SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } } | SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); } | SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); } | SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); } |
@Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L); assertSpanner("Belinda", 10, "jones", spanner); } | public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } | SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } } | SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); } | SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); } | SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); } |
@Test public void testDelete() throws Exception { server.expect(requestTo("/1")).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.NO_CONTENT)); Spanner susan = aSpanner().withId(1L).named("Susan").build(); service.delete(susan); server.verify(); } | @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } | SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } } | SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); } | SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); } | SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); } |
@Test public void findAllTest() throws Exception{ MockUtils.mockGetTest("/mongo/findAll",mockMvc); } | @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } | MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } } | MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } } | MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); } | MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); } |
@Test public void updateTest() throws Exception{ Book book = new Book(); book.setId("4"); book.setPrice(130); book.setName("VUE从入门到放弃"); book.setInfo("前端框架--更新"); Gson gson = new Gson(); String params = gson.toJson(book); MvcResult mvcResult = MockUtils.mockPostTest("/mongo/delOne",params,mockMvc); String result = mvcResult.getResponse().getContentAsString(); System.out.println("更新对象-->" + result); } | @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } | MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } } | MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } } | MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); } | MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); } |
@Test public void findByLikesTest() throws Exception{ MockUtils.mockGetTest("/mongo/findLikes?search=从",mockMvc); } | @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } | MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } } | MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } } | MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); } | MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); } |
@Test public void testNull(){ int comparisons = sorter.sort(null, new StringComparator(), false); assertEquals(0, comparisons); } | public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } |
@Test public void testNegativeA(){ Classification res = TriangleClassification.classify(-1, 1, 1); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testNegativeB(){ Classification res = TriangleClassification.classify(1, -1, 1); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testNegativeC(){ Classification res = TriangleClassification.classify(1, 1, -1); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testZeroA(){ Classification res = TriangleClassification.classify(0, 1, 1); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testZeroB(){ Classification res = TriangleClassification.classify(1, 0, 1); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testZeroC(){ Classification res = TriangleClassification.classify(1, 1, 0); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testAllNegatives(){ Classification res = TriangleClassification.classify(-1, -1, -1); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testAllZeros(){ Classification res = TriangleClassification.classify(0, 0, 0); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testEquilateral(){ Classification res = TriangleClassification.classify(1, 1, 1); assertEquals(EQUILATERAL, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testLargeEquilateral(){ int edge = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(edge, edge, edge); assertEquals(EQUILATERAL, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testAlreadySorted(){ String[] array = {"a", "b", "c", "d"}; int comparisons = sorter.sort(array, new StringComparator(), false); assertEquals(3, comparisons); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); } | public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } |
@Test public void testIsoscelesAB(){ Classification res = TriangleClassification.classify(2, 2, 1); assertEquals(ISOSCELES, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testIsoscelesAC(){ Classification res = TriangleClassification.classify(2, 1, 2); assertEquals(ISOSCELES, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testIsoscelesBC(){ Classification res = TriangleClassification.classify(1, 2, 2); assertEquals(ISOSCELES, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testTooLargeA(){ Classification res = TriangleClassification.classify(5, 2, 2); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testTooLargeB(){ Classification res = TriangleClassification.classify(2, 5, 2); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testTooLargeC(){ Classification res = TriangleClassification.classify(2, 2, 5); assertEquals(NOT_A_TRIANGLE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testLargeButShorterA(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max-1, max, max); assertEquals(ISOSCELES, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testLargeButShorterB(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max, max-1, max); assertEquals(ISOSCELES, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testLargeButShorterC(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max, max, max-1); assertEquals(ISOSCELES, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testScalene(){ Classification res = TriangleClassification.classify(2, 3, 4); assertEquals(SCALENE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testInverted(){ String[] array = {"d", "c", "b", "a"}; int comparisons = sorter.sort(array, new StringComparator(), false); assertEquals(12, comparisons); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); } | public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } |
@Test public void testLargeScalene(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max, max-1, max-2); assertEquals(SCALENE, res); } | public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } | TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); } |
@Test public void testFailToPeekOnEmpty(){ assertThrows(RuntimeException.class, () -> queue.peek()); } | @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } | MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } } | MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); } | MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); @Override void enqueue(T value); @Override T dequeue(); @Override T peek(); @Override int size(); } | MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); @Override void enqueue(T value); @Override T dequeue(); @Override T peek(); @Override int size(); } |
@Test public void testCopyArrayWrong(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = WRONG; assertEquals(WRONG, foo[0]); } | public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } |
@Test public void testCopyArray(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copy(foo); checkSameData(foo, copy); String ORIGINAL = foo[0]; String WRONG = "WRONG"; copy[0] = WRONG; assertNotEquals(WRONG, foo[0]); assertEquals(ORIGINAL, foo[0]); } | public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } |
@Test public void testCopyMatrixWrong(){ String[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "rows do not have to have same length"}; String[][] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertEquals(WRONG, foo[1][0]); } | public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } | CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } |
@Test public void testCopyMatrix(){ String[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "raws do not have to have same length"}; String[][] copy = CopyExample.copy(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertNotEquals(WRONG, foo[1][0]); assertEquals("Hello", foo[1][0]); } | public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } | CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } |
@Test public void testMutabilityProblem(){ User foo = new User("foo", "bar", 0); MySet<User> users = new MySetHashMap<>(); users.add(foo); assertEquals(1, users.size()); assertTrue(users.isPresent(foo)); foo.setName("changed"); assertEquals(1, users.size()); assertFalse(users.isPresent(foo)); User copy = new User("foo", "bar", 0); assertFalse(users.isPresent(copy)); User changedCopy = new User("changed", "bar", 0); assertEquals(foo, changedCopy); assertFalse(users.isPresent(changedCopy)); foo.setName("foo"); assertTrue(users.isPresent(copy)); } | public void setName(String name) { this.name = name; } | User { public void setName(String name) { this.name = name; } } | User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); } | User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); @Override boolean equals(Object o); @Override int hashCode(); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); int getId(); void setId(int id); } | User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); @Override boolean equals(Object o); @Override int hashCode(); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); int getId(); void setId(int id); } |
@Test public void testEmpty() { assertEquals(0, set.size()); assertTrue(set.isEmpty()); } | @Override public int size() { return map.size(); } | MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } } | MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } } | MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); } | MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); } |
@Test public void testRemove() { int n = set.size(); String element = "foo"; set.add(element); assertTrue(set.isPresent(element)); assertEquals(n + 1, set.size()); set.remove(element); assertFalse(set.isPresent(element)); assertEquals(n, set.size()); } | @Override public void remove(E element) { map.delete(element); } | MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } } | MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } } | MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); } | MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); } |
@Test public void testHashLongToInt(){ assertEquals(0, HashFunctions.hashLongToInt(0)); assertEquals(42, HashFunctions.hashLongToInt(42)); assertEquals(0, HashFunctions.hashLongToInt(0x1_00_00_00_00L)); assertEquals(5, HashFunctions.hashLongToInt(0x7_00_00_00_05L)); assertEquals(0, HashFunctions.hashLongToInt(0xFF_FF_00_00_00_00L)); } | public static int hashLongToInt(long x) { return (int) x; } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); } |
@Test public void testBase(){ String[] array = {"d", "a", "c", "b"}; sorter.sort(array, new StringComparator(), false); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); } | public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } |
@Test public void testHashLongToIntNegative(){ long one32times = 0xFF_FF_FF_FFL; assertTrue(one32times > 2_000_000_000); assertEquals(-1, HashFunctions.hashLongToInt(one32times)); long singleOne = 0x80_00_00_00L; assertTrue(singleOne > 2_000_000_000); int hashed = HashFunctions.hashLongToInt(singleOne); assertTrue(hashed < -2_000_000_000); assertEquals(Integer.MIN_VALUE, hashed); } | public static int hashLongToInt(long x) { return (int) x; } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); } | HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); } |
@Test public void testHashLongToIntRevised(){ long x = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; long w = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0001_0000L; long z = 0b0001_0001_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; assertNotEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(w)); assertEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(z)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(w)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(z)); } | public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } | HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } } | HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } } | HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); } | HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); } |
@Test public void testShortestPath_simple() { Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(1, 2); assertNotNull(path); assertEquals(2, path.size()); assertEquals(1, (int) path.get(0)); assertEquals(2, (int) path.get(1)); } | @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } |
@Test public void testShortestPath_complex() { Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(2, 8); assertNotNull(path); assertEquals(4, path.size()); assertEquals(2, (int) path.get(0)); assertEquals(3, (int) path.get(1)); assertEquals(6, (int) path.get(2)); assertEquals(8, (int) path.get(3)); } | @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } |
@Test public void testNoPathBFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(3, 9); assertNull(path); } | @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } |
@Test public void testNoPathDFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathDFS(10, 4); assertNull(path); } | @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } | UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } |
@Test public void testConnected(){ Graph<Integer> graph = createGraph(); Set<Integer> left = graph.findConnected(3); Set<Integer> right = graph.findConnected(10); assertEquals(8, left.size()); assertEquals(2, right.size()); } | @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } | UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } } | UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } } | UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } | UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); } |
@Test public void testMultiGenerics(){ GenericExample<String> example = new GenericExample<>(); GenericExample.MyPair<String, Integer> pair = example.createPair("foo", 5); assertNotNull(pair); assertEquals("foo", pair.x); assertEquals((Integer)5, pair.y); GenericExample.MyPair<String, String> other = example.createPair("foo", "bar"); assertNotNull(other); assertEquals("foo", other.x); assertEquals("bar", other.y); } | public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } | GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } } | GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } } | GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } Object identityObject(Object x); T identityGeneric(T x); Z identityGenericOnMethod(T t, Z z); MyPair<T,Z> createPair(T t, Z z); Comparable max(Comparable x, Comparable y); Z maxWithGenerics(Z x, Z y); } | GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } Object identityObject(Object x); T identityGeneric(T x); Z identityGenericOnMethod(T t, Z z); MyPair<T,Z> createPair(T t, Z z); Comparable max(Comparable x, Comparable y); Z maxWithGenerics(Z x, Z y); } |
@Test public void testBase(){ int[] array = {1, 2, 3}; int res = ArrayExample.sum(array); assertEquals(6, res); } | public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); } |
@Test public void testNegative(){ int[] array = new int[3]; array[0] = -2; array[1] = -1; int res = ArrayExample.sum(array); assertEquals(-3, res); } | public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); } |
@Test public void testNearly(){ String[] array = {"c", "b", "a", "d", "e", "f"}; int optimized = sorter.sort(array, new StringComparator(), true); array = new String[]{"c", "b", "a", "d", "e", "f"}; int base = sorter.sort(array, new StringComparator(), false); assertTrue(optimized < base); assertTrue(optimized < base/2); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); assertEquals("e", array[4]); assertEquals("f", array[5]); } | public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } |
@Test public void testLarge(){ int x = 1_000_000_000; int[] array = {x, x, x}; int res = ArrayExample.sum(array); assertTrue(res < 0); } | public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); } | ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); } |
@Test public void testSolveByHeavierFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByHeavierFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(47d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); } | public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } | GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } } | GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } } | GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); } | GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); } |
@Test public void testSolveByLighterFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByLighterFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(44d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); } | public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } | GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } } | GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } } | GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); } | GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); } |
@Test public void testSolveByBestRatioFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] heavier = GreedyForKnapsack.solveByHeavierFirst(p.getProblem()); boolean[] ratio = GreedyForKnapsack.solveByBestRatioFirst(p.getProblem()); assertArrayEquals(heavier, ratio); } | public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.getValue() / b.getWeight(); double diff = ra - rb; if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } | GreedyForKnapsack { public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.getValue() / b.getWeight(); double diff = ra - rb; if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } } | GreedyForKnapsack { public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.getValue() / b.getWeight(); double diff = ra - rb; if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } } | GreedyForKnapsack { public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.getValue() / b.getWeight(); double diff = ra - rb; if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); } | GreedyForKnapsack { public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.getValue() / b.getWeight(); double diff = ra - rb; if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); } |
@Test public void testDecreaseSize(){ String dna = "AAAGTACCTGAGTAAAGTACCTGAGTAAAGTACCTGAGTTTTGCTGCTGCTGCTGCTGCTGCTGCTGCTGCTTTTTTT"; checkPreserveInformation(dna); int nonCompressedSize = dna.getBytes(StandardCharsets.UTF_8).length; byte[] compressed = DnaCompressor.compress(dna); assertTrue(compressed.length < nonCompressedSize); double ratio = (double) compressed.length / (double) nonCompressedSize; assertTrue(ratio < 0.33); assertTrue(ratio >= 0.25); } | public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } static byte[] compress(String dna); static String decompress(byte[] data); } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } static byte[] compress(String dna); static String decompress(byte[] data); } |
@Test public void testIncreaseSize(){ String dna = "A"; checkPreserveInformation(dna); int nonCompressedSize = dna.getBytes(StandardCharsets.UTF_8).length; byte[] compressed = DnaCompressor.compress(dna); assertTrue(compressed.length > nonCompressedSize); } | public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } static byte[] compress(String dna); static String decompress(byte[] data); } | DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } static byte[] compress(String dna); static String decompress(byte[] data); } |
@Test public void testByte(){ byte val = 5; BitReader reader = new BitReader(new byte[]{val}); byte res = reader.readByte(); assertEquals(val, res); } | public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testNegativeByte(){ byte val = -125; BitReader reader = new BitReader(new byte[]{val}); byte res = reader.readByte(); assertEquals(val, res); } | public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testBoolean(){ byte val = (byte)0b1000_0000; BitReader reader = new BitReader(new byte[]{val}); boolean b = reader.readBoolean(); assertTrue(b); } | public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testTrueFalseTrue(){ byte val = (byte)0b1010_0000; BitReader reader = new BitReader(new byte[]{val}); assertTrue(reader.readBoolean()); assertFalse(reader.readBoolean()); assertTrue(reader.readBoolean()); } | public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testGameUsers(){ GameUser a = new GameUser("a", 10); GameUser b = new GameUser("b", 5); GameUser c = new GameUser("c", 2); GameUser d = new GameUser("d", 5); GameUser[] array = {a,b,c,d}; sorter.sort(array, new GameUserComparator(), true); assertEquals("c", array[0].getUserId()); assertEquals("b", array[1].getUserId()); assertEquals("d", array[2].getUserId()); assertEquals("a", array[3].getUserId()); } | public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } | OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); } |
@Test public void testSmallInt(){ int val = 5; BitWriter writer = new BitWriter(); writer.write(val); BitReader reader = new BitReader(writer.extract()); int res = reader.readInt(); assertEquals(val, res); } | public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testIntWithNegativeBytes(){ int val = 0b1000_0000_1000_0000; BitWriter writer = new BitWriter(); writer.write(val); BitReader reader = new BitReader(writer.extract()); int res = reader.readInt(); assertEquals(val, res); } | public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testStringChar(){ String val = "abc"; BitWriter writer = new BitWriter(); writer.write(val); BitReader reader = new BitReader(writer.extract()); char a = reader.readChar(); char b = reader.readChar(); char c = reader.readChar(); assertEquals('a', a); assertEquals('b', b); assertEquals('c', c); } | public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } | BitReader { public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } } | BitReader { public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } BitReader(byte[] data); } | BitReader { public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } | BitReader { public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); } |
@Test public void testDepthZero() { assertEquals(0, map.getMaxTreeDepth()); } | @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } | MyMapBinarySearchTree implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } } | MyMapBinarySearchTree implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } } | MyMapBinarySearchTree implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); } | MyMapBinarySearchTree implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); } |
@Test public void testRunnable() { Runnable anonymousClass = new Runnable() { @Override public void run() { System.out.println("Executing method run()"); } }; Runnable lambda = () -> System.out.println("Executing method run()"); LambdaExamples.useRunnable(anonymousClass); LambdaExamples.useRunnable(lambda); LambdaExamples.useRunnable(() -> System.out.println("Executing method run()")); } | public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } | LambdaExamples { public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } } | LambdaExamples { public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } } | LambdaExamples { public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } | LambdaExamples { public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } |
@Test public void testConsumer() { Consumer<String> anonymousClass = new Consumer<String>() { @Override public void accept(String s) { System.out.println(s.toUpperCase()); } }; Consumer<String> lambda = s -> System.out.println(s.toUpperCase()); LambdaExamples.useConsumer(anonymousClass); LambdaExamples.useConsumer(lambda); LambdaExamples.useConsumer(s -> System.out.println(s.toUpperCase())); } | public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } | LambdaExamples { public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } } | LambdaExamples { public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } } | LambdaExamples { public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } | LambdaExamples { public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } |
@Test public void testPredicate() { Predicate<String> anonymousClass = new Predicate<String>() { @Override public boolean test(String s) { return s.length() > 5; } }; Predicate<String> lambda = s -> s.toUpperCase().equals("FOO"); assertNull(LambdaExamples.usePredicate(anonymousClass)); assertNotNull(LambdaExamples.usePredicate(lambda)); assertNotNull(LambdaExamples.usePredicate(s -> { int length = s.length(); return length == 3; } )); } | public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } | LambdaExamples { public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } } | LambdaExamples { public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } } | LambdaExamples { public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } | LambdaExamples { public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } |
@Test public void testFunction(){ Function<String, Integer> anonymousClass = new Function<String, Integer>() { @Override public Integer apply(String s) { return s.length(); } }; Function<String, Integer> lambda = s -> 5; assertEquals(3, LambdaExamples.useFunction(anonymousClass)); assertEquals(5, LambdaExamples.useFunction(lambda)); assertEquals(6, LambdaExamples.useFunction(s -> s.length() * 2)); } | public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } | LambdaExamples { public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } } | LambdaExamples { public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } } | LambdaExamples { public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } | LambdaExamples { public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); } |
@Test public void testIterable(){ MyIterableLinkedList<String> data = new MyIterableLinkedList<>(); data.add("a"); data.add("b"); data.add("c"); String buffer = ""; for(String value : data){ buffer += value; } assertEquals("abc", buffer); } | public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } | MyIterableLinkedList implements Iterable<T> { public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } } | MyIterableLinkedList implements Iterable<T> { public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } } | MyIterableLinkedList implements Iterable<T> { public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); } | MyIterableLinkedList implements Iterable<T> { public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); } |
@Test public void testEmpty(){ MyIterableLinkedList<Integer> data = new MyIterableLinkedList<>(); assertEquals(0, data.size()); } | public int size() { return size; } | MyIterableLinkedList implements Iterable<T> { public int size() { return size; } } | MyIterableLinkedList implements Iterable<T> { public int size() { return size; } } | MyIterableLinkedList implements Iterable<T> { public int size() { return size; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); } | MyIterableLinkedList implements Iterable<T> { public int size() { return size; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); } |
@Test public void test(){ AllPathsGraph<String> graph = new AllPathsGraph<>(); graph.addEdge("0","X"); graph.addEdge("X","1"); graph.addEdge("X","Y"); graph.addEdge("1","2"); graph.addEdge("2","Y"); graph.addEdge("1","3"); graph.addEdge("3","4"); graph.addEdge("3","5"); graph.addEdge("4","5"); List<List<String>> paths = graph.findAllPaths("X","5"); assertEquals(4, paths.size()); assertTrue(paths.stream().anyMatch(p -> p.size() == 4)); assertTrue(paths.stream().anyMatch(p -> p.size() == 5)); assertTrue(paths.stream().anyMatch(p -> p.size() == 6)); assertTrue(paths.stream().anyMatch(p -> p.size() == 7)); } | public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> paths = new ArrayList<>(); dfs(paths, stack, start, end); return paths; } | AllPathsGraph extends UndirectedGraph<V> { public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> paths = new ArrayList<>(); dfs(paths, stack, start, end); return paths; } } | AllPathsGraph extends UndirectedGraph<V> { public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> paths = new ArrayList<>(); dfs(paths, stack, start, end); return paths; } } | AllPathsGraph extends UndirectedGraph<V> { public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> paths = new ArrayList<>(); dfs(paths, stack, start, end); return paths; } List<List<V>> findAllPaths(V start, V end); } | AllPathsGraph extends UndirectedGraph<V> { public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> paths = new ArrayList<>(); dfs(paths, stack, start, end); return paths; } List<List<V>> findAllPaths(V start, V end); } |
@Test public void testOutOfIndex(){ MyIterableLinkedList<String> data = new MyIterableLinkedList<>(); assertThrows(IndexOutOfBoundsException.class, () -> data.get(-5)); assertThrows(IndexOutOfBoundsException.class, () -> data.get(42)); } | public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } assert false; return null; } | MyIterableLinkedList implements Iterable<T> { public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } assert false; return null; } } | MyIterableLinkedList implements Iterable<T> { public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } assert false; return null; } } | MyIterableLinkedList implements Iterable<T> { public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } assert false; return null; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); } | MyIterableLinkedList implements Iterable<T> { public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } assert false; return null; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); } |
@Test public void testIterable(){ MyIterableHashMap<Integer, String> map = new MyIterableHashMap<>(); map.put(0, "a"); map.put(1, "b"); map.put(2, "c"); String buffer = ""; for(String value : map){ buffer += value; } assertEquals(3, buffer.length()); assertTrue(buffer.contains("a")); assertTrue(buffer.contains("b")); assertTrue(buffer.contains("c")); } | @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ entry.value = value; return; } } list.add(new Entry(key, value)); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ entry.value = value; return; } } list.add(new Entry(key, value)); } } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ entry.value = value; return; } } list.add(new Entry(key, value)); } MyIterableHashMap(); MyIterableHashMap(int capacity); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ entry.value = value; return; } } list.add(new Entry(key, value)); } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ entry.value = value; return; } } list.add(new Entry(key, value)); } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); } |
@Test public void testEmpty() { MyIterableHashMap<String, Integer> map = new MyIterableHashMap<>(); assertEquals(0, map.size()); assertTrue(map.isEmpty()); } | @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } MyIterableHashMap(); MyIterableHashMap(int capacity); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); } |
@Test public void testDelete() { MyIterableHashMap<String, Integer> map = new MyIterableHashMap<>(); int n = map.size(); String key = "foo"; int x = 42; map.put(key, x); assertEquals(x, map.get(key).intValue()); assertEquals(n + 1, map.size()); map.delete(key); assertNull(map.get(key)); assertEquals(n, map.size()); } | @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; return; } } } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; return; } } } } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; return; } } } MyIterableHashMap(); MyIterableHashMap(int capacity); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; return; } } } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); } | MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; return; } } } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); } |
@Test public void testSingleLetter(){ Matcher matcher = new Matcher("a"); assertFalse(matcher.match("")); assertFalse(matcher.match("b")); assertFalse(matcher.match("ab")); assertTrue(matcher.match("a")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testOr(){ Matcher matcher = new Matcher("(a|b)"); assertFalse(matcher.match("")); assertFalse(matcher.match("ab")); assertFalse(matcher.match("c")); assertTrue(matcher.match("a")); assertTrue(matcher.match("b")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testMultiLetterOr(){ Matcher matcher = new Matcher("(ab|cd)"); assertFalse(matcher.match("")); assertFalse(matcher.match("a")); assertFalse(matcher.match("b")); assertFalse(matcher.match("c")); assertFalse(matcher.match("d")); assertFalse(matcher.match("abd")); assertFalse(matcher.match("acd")); assertTrue(matcher.match("ab")); assertTrue(matcher.match("cd")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testMultipleOr(){ Matcher matcher = new Matcher("((a|b)|c)"); assertFalse(matcher.match("")); assertFalse(matcher.match("ab")); assertFalse(matcher.match("ac")); assertFalse(matcher.match("bc")); assertTrue(matcher.match("a")); assertTrue(matcher.match("b")); assertTrue(matcher.match("c")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testOrWithFollowing(){ Matcher matcher = new Matcher("(a|b)c"); assertFalse(matcher.match("ab")); assertFalse(matcher.match("c")); assertFalse(matcher.match("")); assertTrue(matcher.match("ac")); assertTrue(matcher.match("bc")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testStar(){ Matcher matcher = new Matcher("a*"); assertFalse(matcher.match("b")); assertFalse(matcher.match("ba")); assertTrue(matcher.match("")); assertTrue(matcher.match("a")); assertTrue(matcher.match("aa")); assertTrue(matcher.match("aaa")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testDepthZero() { assertEquals(0, map.getMaxTreeDepth()); } | @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } | TernaryTreeMap implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } } | TernaryTreeMap implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } } | TernaryTreeMap implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); } | TernaryTreeMap implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); } |
@Test public void testStarWithFollowing(){ Matcher matcher = new Matcher("a*b"); assertFalse(matcher.match("")); assertFalse(matcher.match("c")); assertTrue(matcher.match("b")); assertTrue(matcher.match("ab")); assertTrue(matcher.match("aab")); assertTrue(matcher.match("aaab")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testAnySingle(){ Matcher matcher = new Matcher("."); assertFalse(matcher.match("")); assertFalse(matcher.match("ab")); assertTrue(matcher.match("a")); assertTrue(matcher.match("b")); assertTrue(matcher.match(".")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testAll() { Matcher matcher = new Matcher(".*"); assertTrue(matcher.match("")); assertTrue(matcher.match(".")); assertTrue(matcher.match("a")); assertTrue(matcher.match("ab")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testHasLetter() { Matcher matcher = new Matcher(".*a.*"); assertFalse(matcher.match("")); assertFalse(matcher.match("b")); assertFalse(matcher.match("bc")); assertTrue(matcher.match("a")); assertTrue(matcher.match("ab")); assertTrue(matcher.match("ca")); assertTrue(matcher.match("cab")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testExampleFromBook(){ Matcher matcher = new Matcher(".*(a*b|ac)d.*"); assertFalse(matcher.match("ac")); assertFalse(matcher.match("ad")); assertFalse(matcher.match("aaa")); assertFalse(matcher.match("add")); assertFalse(matcher.match("bcd")); assertFalse(matcher.match("babaaa")); assertFalse(matcher.match("babbaaa")); assertTrue(matcher.match("abd")); assertTrue(matcher.match("abccbd")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testSlideExample(){ Matcher matcher = new Matcher("(a*|(bc)*)z"); assertFalse(matcher.match("")); assertFalse(matcher.match("a")); assertFalse(matcher.match("bc")); assertFalse(matcher.match("bz")); assertFalse(matcher.match("cz")); assertFalse(matcher.match("abcz")); assertFalse(matcher.match("bcaz")); assertTrue(matcher.match("z")); assertTrue(matcher.match("az")); assertTrue(matcher.match("aaaaaaz")); assertTrue(matcher.match("bcz")); assertTrue(matcher.match("bcbcbcbcz")); } | public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } | Matcher { public boolean match(String txt) { Objects.requireNonNull(txt); int acceptanceState = regex.length(); Set<Integer> vertices = nfsm.findConnected(0); for (int i = 0; i < txt.length(); i++) { char current = txt.charAt(i); if (current == '*' || current == '|' || current == '(' || current == ')') { throw new IllegalArgumentException("text contains the metacharacter '" + txt.charAt(i) + "'"); } Set<Integer> match = new HashSet<>(); for (int v : vertices) { if (v == acceptanceState) { continue; } if ((regex.charAt(v) == txt.charAt(i)) || regex.charAt(v) == '.') { match.add(v + 1); } } if(match.isEmpty()){ return false; } vertices = nfsm.findConnected(match); } return vertices.contains(acceptanceState); } Matcher(String regex); boolean match(String txt); } |
@Test public void testEmpty(){ assertEquals(0, data.size()); } | public int size() { return size; } | MyArrayListInteger { public int size() { return size; } } | MyArrayListInteger { public int size() { return size; } MyArrayListInteger(); MyArrayListInteger(int maxSize); } | MyArrayListInteger { public int size() { return size; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); } | MyArrayListInteger { public int size() { return size; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); } |
@Test public void testOutOfIndex(){ assertNull(data.get(-5)); assertNull(data.get(42)); } | public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } | MyArrayListInteger { public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } } | MyArrayListInteger { public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } MyArrayListInteger(); MyArrayListInteger(int maxSize); } | MyArrayListInteger { public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); } | MyArrayListInteger { public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); } |
@Test public void testPublishAndConsumeEvents() throws Exception { UnitOfWork<Message<?>> uow = DefaultUnitOfWork.startAndGet(null); testSubject.publish(GenericEventMessage.asEventMessage("Test1"), GenericEventMessage.asEventMessage("Test2"), GenericEventMessage.asEventMessage("Test3")); uow.commit(); TrackingEventStream stream = testSubject.openStream(null); List<String> received = new ArrayList<>(); while(stream.hasNextAvailable(100, TimeUnit.MILLISECONDS)) { received.add(stream.nextAvailable().getPayload().toString()); } stream.close(); assertEquals(Arrays.asList("Test1", "Test2", "Test3"), received); } | @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } | AxonDBEventStore extends AbstractEventStore { @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } } | AxonDBEventStore extends AbstractEventStore { @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer); AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer, EventUpcaster upcasterChain); AxonDBEventStore(AxonDBConfiguration configuration, Serializer snapshotSerializer, Serializer eventSerializer, EventUpcaster upcasterChain); } | AxonDBEventStore extends AbstractEventStore { @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer); AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer, EventUpcaster upcasterChain); AxonDBEventStore(AxonDBConfiguration configuration, Serializer snapshotSerializer, Serializer eventSerializer, EventUpcaster upcasterChain); @Override TrackingEventStream openStream(TrackingToken trackingToken); QueryResultStream query(String query, boolean liveUpdates); } | AxonDBEventStore extends AbstractEventStore { @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer); AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer, EventUpcaster upcasterChain); AxonDBEventStore(AxonDBConfiguration configuration, Serializer snapshotSerializer, Serializer eventSerializer, EventUpcaster upcasterChain); @Override TrackingEventStream openStream(TrackingToken trackingToken); QueryResultStream query(String query, boolean liveUpdates); } |