repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-properties/src/main/java/com/baeldung/maven/properties/PropertiesReader.java
maven-modules/maven-properties/src/main/java/com/baeldung/maven/properties/PropertiesReader.java
package com.baeldung.maven.properties; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Reads properties from one file. * * @author Donato Rimenti */ public class PropertiesReader { /** * Properties managed by this reader. */ private Properties properties; /** * Reads the property file with the given name. * * @param propertyFileName the name of the property file to read * @throws IOException if the file is not found or there's a problem reading it */ public PropertiesReader(String propertyFileName) throws IOException { InputStream is = getClass().getClassLoader() .getResourceAsStream(propertyFileName); this.properties = new Properties(); this.properties.load(is); } /** * Gets the property with the given name from the property file. * @param propertyName the name of the property to read * @return the property with the given name */ public String getProperty(String propertyName) { return this.properties.getProperty(propertyName); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-dependency/src/main/java/com/baeldung/Main.java
maven-modules/maven-dependency/src/main/java/com/baeldung/Main.java
package com.baeldung; import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { StringUtils.isBlank(" "); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-copy-files/copy-rename-maven-plugin/src/test/java/com/baeldung/CopyFileUnitTest.java
maven-modules/maven-copy-files/copy-rename-maven-plugin/src/test/java/com/baeldung/CopyFileUnitTest.java
package com.baeldung; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class CopyFileUnitTest { @Test public void whenCopyingAFileFromSourceToDestination_thenFileShouldBeInDestination() { File destinationFile = new File("target/destination-folder/foo.txt"); assertEquals(true, destinationFile.exists()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-copy-files/maven-antrun-plugin/src/test/java/com/baeldung/CopyFileUnitTest.java
maven-modules/maven-copy-files/maven-antrun-plugin/src/test/java/com/baeldung/CopyFileUnitTest.java
package com.baeldung; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class CopyFileUnitTest { @Test public void whenCopyingAFileFromSourceToDestination_thenFileShouldBeInDestination() { File destinationFile = new File("target/destination-folder/foo.txt"); assertEquals(true, destinationFile.exists()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-copy-files/maven-resources-plugin/src/test/java/com/baeldung/CopyFileUnitTest.java
maven-modules/maven-copy-files/maven-resources-plugin/src/test/java/com/baeldung/CopyFileUnitTest.java
package com.baeldung; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class CopyFileUnitTest { @Test public void whenCopyingAFileFromSourceToDestination_thenFileShouldBeInDestination() { File destinationFile = new File("target/destination-folder/foo.txt"); assertEquals(true, destinationFile.exists()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/spring-bom/src/test/java/com/baeldung/SpringContextTest.java
maven-modules/spring-bom/src/test/java/com/baeldung/SpringContextTest.java
package com.baeldung; import org.junit.Test; import com.baeldung.spring.bom.HelloWorldApp; public class SpringContextTest { @Test public final void testMain() throws Exception { HelloWorldApp.main(null); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java
maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java
package com.baeldung.spring.bom; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class HelloWorldApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorldBean helloWorldBean = ctx.getBean(HelloWorldBean.class); System.out.println(helloWorldBean.sayHello()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java
maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java
package com.baeldung.spring.bom; public class HelloWorldBean { public String sayHello() { return "Hello World With Maven BOM"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java
maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java
package com.baeldung.spring.bom; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HelloWorldConfig { @Bean public HelloWorldBean helloWorldBean() { return new HelloWorldBean(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-build-lifecycle/src/test/java/com/baeldung/mavenlifecycle/CourseAppIT.java
maven-modules/maven-build-lifecycle/src/test/java/com/baeldung/mavenlifecycle/CourseAppIT.java
package com.baeldung.mavenlifecycle; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class CourseAppIT { @Test void givenIntegrationTest_whenGetCourse_ThenCourseShouldBePresent() { CourseApp courseApp = new CourseApp(); assertEquals("Baeldung Spring Masterclass", courseApp.getCourse()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-build-lifecycle/src/test/java/com/baeldung/mavenlifecycle/CourseAppUnitTest.java
maven-modules/maven-build-lifecycle/src/test/java/com/baeldung/mavenlifecycle/CourseAppUnitTest.java
package com.baeldung.mavenlifecycle; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class CourseAppUnitTest { @Test void whenGetCourse_ThenCourseShouldBePresent() { CourseApp courseApp = new CourseApp(); assertEquals("Baeldung Spring Masterclass", courseApp.getCourse()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-build-lifecycle/src/main/java/com/baeldung/mavenlifecycle/CourseApp.java
maven-modules/maven-build-lifecycle/src/main/java/com/baeldung/mavenlifecycle/CourseApp.java
package com.baeldung.mavenlifecycle; public class CourseApp { public String getCourse() { return "Baeldung Spring Masterclass"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/dependencygraph/module2/src/main/java/com/baeldung/module2/TestB.java
maven-modules/dependencygraph/module2/src/main/java/com/baeldung/module2/TestB.java
package com.baeldung.module2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestB { public Logger getLogger() { return LoggerFactory.getLogger(TestB.class); } public String getName(String name) { return "Hello" + name; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/dependencygraph/module1/src/main/java/com/baeldung/module1/TestA.java
maven-modules/dependencygraph/module1/src/main/java/com/baeldung/module1/TestA.java
package com.baeldung.module1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baeldung.module2.TestB; public class TestA { public Logger getLogger() { return LoggerFactory.getLogger(TestA.class); } public void printName() { TestB testb = new TestB(); testb.getName("baeldung"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/compiler-plugin-java-9/src/main/java/module-info.java
maven-modules/compiler-plugin-java-9/src/main/java/module-info.java
module com.baeldung.maven.java9 { requires java.xml; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java
maven-modules/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java
package com.baeldung.maven.java9; import static javax.xml.XMLConstants.XML_NS_PREFIX; public class MavenCompilerPlugin { public static void main(String[] args) { System.out.println("The XML namespace prefix is: " + XML_NS_PREFIX); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-builder-plugin/src/main/newsrc/com/baeldung/database/DataConnection.java
maven-modules/maven-builder-plugin/src/main/newsrc/com/baeldung/database/DataConnection.java
package com.baeldung.database; public class DataConnection { public static String temp(){ return "secondary source directory"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-builder-plugin/src/main/java/com/baeldung/maven/plugin/MainApp.java
maven-modules/maven-builder-plugin/src/main/java/com/baeldung/maven/plugin/MainApp.java
package com.baeldung.maven.plugin; import com.baeldung.database.DataConnection; public class MainApp { public static void main(String args[]){ System.out.println(DataConnection.temp()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-unused-dependencies/src/main/java/com/baeldung/mavendependencyplugin/UnusedDependenciesExample.java
maven-modules/maven-unused-dependencies/src/main/java/com/baeldung/mavendependencyplugin/UnusedDependenciesExample.java
package com.baeldung.mavendependencyplugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UnusedDependenciesExample { /** * When the Maven dependency analyzer analyzes the code, it will see that the slf4j dependency is being used in this method. * * @return the slf4j {@link Logger}. */ public Logger getLogger() { return LoggerFactory.getLogger(UnusedDependenciesExample.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/resume-from/business/src/main/java/Main.java
maven-modules/resume-from/business/src/main/java/Main.java
public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-custom-plugin/counter-maven-plugin/src/main/java/com/baeldung/maven/plugin/validator/DependencyCounterMojo.java
maven-modules/maven-custom-plugin/counter-maven-plugin/src/main/java/com/baeldung/maven/plugin/validator/DependencyCounterMojo.java
package com.baeldung.maven.plugin.validator; import java.util.List; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; /** * Counts the number of maven dependencies of a project. * * It can be filtered by scope. * */ @Mojo(name = "dependency-counter", defaultPhase = LifecyclePhase.COMPILE) public class DependencyCounterMojo extends AbstractMojo { /** * Scope to filter the dependencies. */ @Parameter(property = "scope") String scope; /** * Gives access to the Maven project information. */ @Parameter(defaultValue = "${project}", required = true, readonly = true) MavenProject project; public void execute() throws MojoExecutionException, MojoFailureException { List<Dependency> dependencies = project.getDependencies(); long numDependencies = dependencies.stream() .filter(d -> (scope == null || scope.isEmpty()) || scope.equals(d.getScope())) .count(); getLog().info("Number of dependencies: " + numDependencies); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-plugins/custom-rule/src/main/java/com/baeldung/enforcer/MyCustomRule.java
maven-modules/maven-plugins/custom-rule/src/main/java/com/baeldung/enforcer/MyCustomRule.java
/* * Copyright (c) 2019 PloyRef * Created by Seun Matt <smatt382@gmail.com> * on 19 - 2 - 2019 */ package com.baeldung.enforcer; import org.apache.maven.enforcer.rule.api.EnforcerRule; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; public class MyCustomRule implements EnforcerRule { public void execute(EnforcerRuleHelper enforcerRuleHelper) throws EnforcerRuleException { try { String groupId = (String) enforcerRuleHelper.evaluate("${project.groupId}"); if (groupId == null || !groupId.startsWith("com.baeldung")) { throw new EnforcerRuleException("Project group id does not start with com.baeldung"); } } catch (ExpressionEvaluationException ex ) { throw new EnforcerRuleException( "Unable to lookup an expression " + ex.getLocalizedMessage(), ex ); } } public boolean isCacheable() { return false; } public boolean isResultValid(EnforcerRule enforcerRule) { return false; } public String getCacheId() { return null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-plugins/jaxws/src/test/java/com/baeldung/soap/ws/client/CountryServiceClientUnitTest.java
maven-modules/maven-plugins/jaxws/src/test/java/com/baeldung/soap/ws/client/CountryServiceClientUnitTest.java
package com.baeldung.soap.ws.client; import org.junit.jupiter.api.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; class CountryServiceClientUnitTest { CountryServiceClient countryServiceClient; CountryService countryService; @BeforeEach void setUp() { countryService = mock(CountryService.class); countryServiceClient = new CountryServiceClient(countryService); } @DisplayName("Get capital by country name when country not found") @Test void givenCountryDoesNotExist_whenGetCapitalByCountryName_thenThrowsCountryNotFoundException() { doThrow(CountryNotFoundException.class).when(countryService).findByName(any()); Assertions.assertThrows(CountryNotFoundException.class, () -> countryServiceClient.getCapitalByCountryName(any())); } @DisplayName("Get capital by country name when country is India then should return capital") @Test void givenCountryIndia_whenGetCapitalByCountryName_thenShouldReturnCapital() { Country country = mock(Country.class); doReturn("New Delhi").when(country).getCapital(); doReturn(country).when(countryService).findByName("India"); Assertions.assertEquals("New Delhi", countryServiceClient.getCapitalByCountryName("India")); } @DisplayName("Get population by country name when country not found") @Test void givenCountryDoesNotExist_getPopulationByCountryName_thenThrowsCountryNotFoundException() { doThrow(CountryNotFoundException.class).when(countryService).findByName(any()); Assertions.assertThrows(CountryNotFoundException.class, () -> countryServiceClient.getPopulationByCountryName(any())); } @DisplayName("Get population by country name when country is India then should return population") @Test void givenCountryIndia_getPopulationByCountryName_thenShouldReturnPopulation() { Country country = mock(Country.class); doReturn(1000000).when(country).getPopulation(); doReturn(country).when(countryService).findByName("India"); Assertions.assertEquals(1000000, countryServiceClient.getPopulationByCountryName("India")); } @DisplayName("Get currency by country name when country not found") @Test void givenCountryDoesNotExist_getCurrencyByCountryName_thenThrowsCountryNotFoundException() { doThrow(CountryNotFoundException.class).when(countryService).findByName(any()); Assertions.assertThrows(CountryNotFoundException.class, () -> countryServiceClient.getCurrencyByCountryName(any())); } @DisplayName("Get currency by country name when country is India then should return currency") @Test void givenCountryIndia_getCurrencyByCountryName_thenShouldReturnCurrency() { Country country = mock(Country.class); doReturn(Currency.INR).when(country).getCurrency(); doReturn(country).when(countryService).findByName("India"); Assertions.assertEquals(Currency.INR, countryServiceClient.getCurrencyByCountryName("India")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryNotFoundException.java
maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryNotFoundException.java
package com.baeldung.soap.ws.client; public class CountryNotFoundException extends RuntimeException { public CountryNotFoundException() { super("Country not found!"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryServiceClient.java
maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryServiceClient.java
package com.baeldung.soap.ws.client; import java.util.Optional; public class CountryServiceClient { private CountryService countryService; public CountryServiceClient(CountryService countryService) { this.countryService = countryService; } public String getCapitalByCountryName(String countryName) { return Optional.of(countryService.findByName(countryName)) .map(Country::getCapital).orElseThrow(CountryNotFoundException::new); } public int getPopulationByCountryName(String countryName) { return Optional.of(countryService.findByName(countryName)) .map(Country::getPopulation).orElseThrow(CountryNotFoundException::new); } public Currency getCurrencyByCountryName(String countryName) { return Optional.of(countryService.findByName(countryName)) .map(Country::getCurrency).orElseThrow(CountryNotFoundException::new); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/maven-modules/maven-plugins/spotless/src/main/java/com/baeldung/spotless/FizzBuzz.java
maven-modules/maven-plugins/spotless/src/main/java/com/baeldung/spotless/FizzBuzz.java
package com.baeldung.spotless; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.Nullable; public class FizzBuzz { @Nullable static String pi = "3.14"; public static void main(String[] args) { Map<Integer, String> dividers = new HashMap<>(); dividers.put(3, "Fizz"); dividers.put(5, "Buzz"); int limit = 100; for (int i = 1; i <= limit; i++) { StringBuilder output = new StringBuilder(); for (Map.Entry<Integer, String> entry : dividers.entrySet()) { if (i % entry.getKey() == 0) { output.append(entry.getValue()); } } if (!(output.length() == 0)) { System.out.println(output); } else { System.out.println(i); } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
package com.baeldung.trie; import org.junit.Test; import org.junit.jupiter.api.Assertions; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class TrieUnitTest { @Test public void whenEmptyTrie_thenNoElements() { Trie trie = new Trie(); assertFalse(trie.isEmpty()); } @Test public void givenATrie_whenAddingElements_thenTrieNotEmpty() { Trie trie = createExampleTrie(); assertFalse(trie.isEmpty()); } @Test public void givenATrie_whenAddingElements_thenTrieHasThoseElements() { Trie trie = createExampleTrie(); assertFalse(trie.containsNode("3")); assertFalse(trie.containsNode("vida")); assertTrue(trie.containsNode("Programming")); assertTrue(trie.containsNode("is")); assertTrue(trie.containsNode("a")); assertTrue(trie.containsNode("way")); assertTrue(trie.containsNode("of")); assertTrue(trie.containsNode("life")); } @Test public void givenATrie_whenLookingForNonExistingElement_thenReturnsFalse() { Trie trie = createExampleTrie(); assertFalse(trie.containsNode("99")); } @Test public void givenATrie_whenDeletingElements_thenTreeDoesNotContainThoseElements() { Trie trie = createExampleTrie(); assertTrue(trie.containsNode("Programming")); trie.delete("Programming"); assertFalse(trie.containsNode("Programming")); } @Test public void givenATrie_whenDeletingOverlappingElements_thenDontDeleteSubElement() { Trie trie1 = new Trie(); trie1.insert("pie"); trie1.insert("pies"); trie1.delete("pies"); Assertions.assertTrue(trie1.containsNode("pie")); } private Trie createExampleTrie() { Trie trie = new Trie(); trie.insert("Programming"); trie.insert("is"); trie.insert("a"); trie.insert("way"); trie.insert("of"); trie.insert("life"); return trie; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java
data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java
package com.baeldung.graph; import static org.junit.Assert.assertEquals; import org.junit.Test; public class GraphUnitTest { @Test public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() { Graph graph = createGraph(); assertEquals("[Bob, Rob, Maria, Alice, Mark]", GraphTraversal.depthFirstTraversal(graph, "Bob").toString()); } @Test public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() { Graph graph = createGraph(); assertEquals("[Bob, Alice, Rob, Mark, Maria]", GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); } @Test public void givenAGraph_whenRemoveVertex_thenVertedNotFound() { Graph graph = createGraph(); assertEquals("[Bob, Alice, Rob, Mark, Maria]", GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); graph.removeVertex("Maria"); assertEquals("[Bob, Alice, Rob, Mark]", GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); } Graph createGraph() { Graph graph = new Graph(); graph.addVertex("Bob"); graph.addVertex("Alice"); graph.addVertex("Mark"); graph.addVertex("Rob"); graph.addVertex("Maria"); graph.addEdge("Bob", "Alice"); graph.addEdge("Bob", "Rob"); graph.addEdge("Alice", "Mark"); graph.addEdge("Rob", "Mark"); graph.addEdge("Alice", "Maria"); graph.addEdge("Rob", "Maria"); return graph; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/test/java/com/baeldung/lrucache/LRUCacheUnitTest.java
data-structures/src/test/java/com/baeldung/lrucache/LRUCacheUnitTest.java
package com.baeldung.lrucache; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.IntStream; import static org.junit.Assert.*; public class LRUCacheUnitTest { @Test public void addSomeDataToCache_WhenGetData_ThenIsEqualWithCacheElement() { LRUCache<String, String> lruCache = new LRUCache<>(3); lruCache.put("1", "test1"); lruCache.put("2", "test2"); lruCache.put("3", "test3"); assertEquals("test1", lruCache.get("1").get()); assertEquals("test2", lruCache.get("2").get()); assertEquals("test3", lruCache.get("3").get()); } @Test public void addDataToCacheToTheNumberOfSize_WhenAddOneMoreData_ThenLeastRecentlyDataWillEvict() { LRUCache<String, String> lruCache = new LRUCache<>(3); lruCache.put("1", "test1"); lruCache.put("2", "test2"); lruCache.put("3", "test3"); lruCache.put("4", "test4"); assertFalse(lruCache.get("1").isPresent()); } @Test public void runMultiThreadTask_WhenPutDataInConcurrentToCache_ThenNoDataLost() throws Exception { final int size = 50; final ExecutorService executorService = Executors.newFixedThreadPool(5); Cache<Integer, String> cache = new LRUCache<>(size); CountDownLatch countDownLatch = new CountDownLatch(size); try { IntStream.range(0, size).<Runnable>mapToObj(key -> () -> { cache.put(key, "value" + key); countDownLatch.countDown(); }).forEach(executorService::submit); countDownLatch.await(); } finally { executorService.shutdown(); } assertEquals(cache.size(), size); IntStream.range(0, size).forEach(i -> assertEquals("value" + i, cache.get(i).get())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
package com.baeldung.tree; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class BinaryTreeUnitTest { @Test public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { BinaryTree bt = createBinaryTree(); assertFalse(bt.isEmpty()); } @Test public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { BinaryTree bt = createBinaryTree(); assertTrue(bt.containsNode(6)); assertTrue(bt.containsNode(4)); assertFalse(bt.containsNode(1)); } @Test public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { BinaryTree bt = createBinaryTree(); int initialSize = bt.getSize(); assertTrue(bt.containsNode(3)); bt.add(3); assertEquals(initialSize, bt.getSize()); } @Test public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { BinaryTree bt = createBinaryTree(); assertFalse(bt.containsNode(99)); } @Test public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { BinaryTree bt = createBinaryTree(); assertTrue(bt.containsNode(9)); bt.delete(9); assertFalse(bt.containsNode(9)); } @Test public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { BinaryTree bt = createBinaryTree(); int initialSize = bt.getSize(); assertFalse(bt.containsNode(99)); bt.delete(99); assertFalse(bt.containsNode(99)); assertEquals(initialSize, bt.getSize()); } @Test public void it_deletes_the_root() { int value = 12; BinaryTree bt = new BinaryTree(); bt.add(value); assertTrue(bt.containsNode(value)); bt.delete(value); assertFalse(bt.containsNode(value)); } @Test public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traverseInOrder(bt.root); System.out.println(); bt.traverseInOrderWithoutRecursion(); } @Test public void givenAnEmptyBinaryTree_WhenTraversingInOrderWithoutRecursion_ThenNoException() { BinaryTree empty = new BinaryTree(); empty.traverseInOrderWithoutRecursion(); } @Test public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traversePreOrder(bt.root); System.out.println(); bt.traversePreOrderWithoutRecursion(); } @Test public void givenAnEmptyBinaryTree_WhenTraversingPreOrderWithoutRecursion_ThenNoException() { BinaryTree empty = new BinaryTree(); empty.traversePreOrderWithoutRecursion(); } @Test public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traversePostOrder(bt.root); System.out.println(); bt.traversePostOrderWithoutRecursion(); } @Test public void givenAnEmptyBinaryTree_WhenTraversingPostOrderWithoutRecursion_ThenNoException() { BinaryTree empty = new BinaryTree(); empty.traversePostOrderWithoutRecursion(); } @Test public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traverseLevelOrder(); } private BinaryTree createBinaryTree() { BinaryTree bt = new BinaryTree(); bt.add(6); bt.add(4); bt.add(8); bt.add(3); bt.add(5); bt.add(7); bt.add(9); return bt; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/trie/TrieNode.java
data-structures/src/main/java/com/baeldung/trie/TrieNode.java
package com.baeldung.trie; import java.util.HashMap; import java.util.Map; class TrieNode { private final Map<Character, TrieNode> children = new HashMap<>(); private boolean endOfWord; Map<Character, TrieNode> getChildren() { return children; } boolean isEndOfWord() { return endOfWord; } void setEndOfWord(boolean endOfWord) { this.endOfWord = endOfWord; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/trie/Trie.java
data-structures/src/main/java/com/baeldung/trie/Trie.java
package com.baeldung.trie; class Trie { private TrieNode root; Trie() { root = new TrieNode(); } void insert(String word) { TrieNode current = root; for (char l : word.toCharArray()) { current = current.getChildren().computeIfAbsent(l, c -> new TrieNode()); } current.setEndOfWord(true); } boolean delete(String word) { return delete(root, word, 0); } boolean containsNode(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.getChildren().get(ch); if (node == null) { return false; } current = node; } return current.isEndOfWord(); } boolean isEmpty() { return root == null; } private boolean delete(TrieNode current, String word, int index) { if (index == word.length()) { if (!current.isEndOfWord()) { return false; } current.setEndOfWord(false); return current.getChildren().isEmpty(); } char ch = word.charAt(index); TrieNode node = current.getChildren().get(ch); if (node == null) { return false; } boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord(); if (shouldDeleteCurrentNode) { current.getChildren().remove(ch); return current.getChildren().isEmpty(); } return false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/graph/Graph.java
data-structures/src/main/java/com/baeldung/graph/Graph.java
package com.baeldung.graph; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Graph { private Map<Vertex, List<Vertex>> adjVertices; Graph() { this.adjVertices = new HashMap<Vertex, List<Vertex>>(); } void addVertex(String label) { adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>()); } void removeVertex(String label) { Vertex v = new Vertex(label); adjVertices.values().stream().forEach(e -> e.remove(v)); adjVertices.remove(new Vertex(label)); } void addEdge(String label1, String label2) { Vertex v1 = new Vertex(label1); Vertex v2 = new Vertex(label2); adjVertices.get(v1).add(v2); adjVertices.get(v2).add(v1); } void removeEdge(String label1, String label2) { Vertex v1 = new Vertex(label1); Vertex v2 = new Vertex(label2); List<Vertex> eV1 = adjVertices.get(v1); List<Vertex> eV2 = adjVertices.get(v2); if (eV1 != null) eV1.remove(v2); if (eV2 != null) eV2.remove(v1); } List<Vertex> getAdjVertices(String label) { return adjVertices.get(new Vertex(label)); } String printGraph() { StringBuffer sb = new StringBuffer(); for(Vertex v : adjVertices.keySet()) { sb.append(v); sb.append(adjVertices.get(v)); } return sb.toString(); } class Vertex { String label; Vertex(String label) { this.label = label; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((label == null) ? 0 : label.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vertex other = (Vertex) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (label == null) { if (other.label != null) return false; } else if (!label.equals(other.label)) return false; return true; } @Override public String toString() { return label; } private Graph getOuterType() { return Graph.this; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/graph/AppToPrintGraph.java
data-structures/src/main/java/com/baeldung/graph/AppToPrintGraph.java
package com.baeldung.graph; import java.util.Set; public class AppToPrintGraph { static Graph createGraph() { Graph graph = new Graph(); graph.addVertex("Bob"); graph.addVertex("Alice"); graph.addVertex("Mark"); graph.addVertex("Rob"); graph.addVertex("Maria"); graph.addEdge("Bob", "Alice"); graph.addEdge("Bob", "Rob"); graph.addEdge("Alice", "Mark"); graph.addEdge("Rob", "Mark"); graph.addEdge("Alice", "Maria"); graph.addEdge("Rob", "Maria"); return graph; } public static void main(String[] args) { Graph graph = createGraph(); Set<String> result = GraphTraversal.breadthFirstTraversal(graph, "Bob"); System.out.println(result.toString()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/graph/GraphTraversal.java
data-structures/src/main/java/com/baeldung/graph/GraphTraversal.java
package com.baeldung.graph; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import java.util.Stack; import com.baeldung.graph.Graph.Vertex; public class GraphTraversal { static Set<String> depthFirstTraversal(Graph graph, String root) { Set<String> visited = new LinkedHashSet<String>(); Stack<String> stack = new Stack<String>(); stack.push(root); while (!stack.isEmpty()) { String vertex = stack.pop(); if (!visited.contains(vertex)) { visited.add(vertex); for (Vertex v : graph.getAdjVertices(vertex)) { stack.push(v.label); } } } return visited; } static Set<String> breadthFirstTraversal(Graph graph, String root) { Set<String> visited = new LinkedHashSet<String>(); Queue<String> queue = new LinkedList<String>(); queue.add(root); visited.add(root); while (!queue.isEmpty()) { String vertex = queue.poll(); for (Vertex v : graph.getAdjVertices(vertex)) { if (!visited.contains(v.label)) { visited.add(v.label); queue.add(v.label); } } } return visited; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/Node.java
data-structures/src/main/java/com/baeldung/lrucache/Node.java
package com.baeldung.lrucache; /** * Created by arash on 09.07.21. */ public class Node<T> implements LinkedListNode<T> { private T value; private DoublyLinkedList<T> list; private LinkedListNode next; private LinkedListNode prev; public Node(T value, LinkedListNode<T> next, DoublyLinkedList<T> list) { this.value = value; this.next = next; this.setPrev(next.getPrev()); this.prev.setNext(this); this.next.setPrev(this); this.list = list; } @Override public boolean hasElement() { return true; } @Override public boolean isEmpty() { return false; } public T getElement() { return value; } public void detach() { this.prev.setNext(this.getNext()); this.next.setPrev(this.getPrev()); } @Override public DoublyLinkedList<T> getListReference() { return this.list; } @Override public LinkedListNode<T> setPrev(LinkedListNode<T> prev) { this.prev = prev; return this; } @Override public LinkedListNode<T> setNext(LinkedListNode<T> next) { this.next = next; return this; } @Override public LinkedListNode<T> getPrev() { return this.prev; } @Override public LinkedListNode<T> getNext() { return this.next; } @Override public LinkedListNode<T> search(T value) { return this.getElement() == value ? this : this.getNext().search(value); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/DummyNode.java
data-structures/src/main/java/com/baeldung/lrucache/DummyNode.java
package com.baeldung.lrucache; /** * Created by arash on 09.07.21. */ public class DummyNode<T> implements LinkedListNode<T> { private DoublyLinkedList<T> list; public DummyNode(DoublyLinkedList<T> list) { this.list = list; } @Override public boolean hasElement() { return false; } @Override public boolean isEmpty() { return true; } @Override public T getElement() throws NullPointerException { throw new NullPointerException(); } @Override public void detach() { return; } @Override public DoublyLinkedList<T> getListReference() { return list; } @Override public LinkedListNode<T> setPrev(LinkedListNode<T> next) { return next; } @Override public LinkedListNode<T> setNext(LinkedListNode<T> prev) { return prev; } @Override public LinkedListNode<T> getPrev() { return this; } @Override public LinkedListNode<T> getNext() { return this; } @Override public LinkedListNode<T> search(T value) { return this; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/LRUCache.java
data-structures/src/main/java/com/baeldung/lrucache/LRUCache.java
package com.baeldung.lrucache; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LRUCache<K, V> implements Cache<K, V> { private int size; private Map<K, LinkedListNode<CacheElement<K, V>>> linkedListNodeMap; private DoublyLinkedList<CacheElement<K, V>> doublyLinkedList; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public LRUCache(int size) { this.size = size; this.linkedListNodeMap = new ConcurrentHashMap<>(size); this.doublyLinkedList = new DoublyLinkedList<>(); } @Override public boolean put(K key, V value) { this.lock.writeLock().lock(); try { CacheElement<K, V> item = new CacheElement<K, V>(key, value); LinkedListNode<CacheElement<K, V>> newNode; if (this.linkedListNodeMap.containsKey(key)) { LinkedListNode<CacheElement<K, V>> node = this.linkedListNodeMap.get(key); newNode = doublyLinkedList.updateAndMoveToFront(node, item); } else { if (this.size() >= this.size) { this.evictElement(); } newNode = this.doublyLinkedList.add(item); } if (newNode.isEmpty()) { return false; } this.linkedListNodeMap.put(key, newNode); return true; } finally { this.lock.writeLock().unlock(); } } @Override public Optional<V> get(K key) { this.lock.readLock().lock(); try { LinkedListNode<CacheElement<K, V>> linkedListNode = this.linkedListNodeMap.get(key); if (linkedListNode != null && !linkedListNode.isEmpty()) { linkedListNodeMap.put(key, this.doublyLinkedList.moveToFront(linkedListNode)); return Optional.of(linkedListNode.getElement().getValue()); } return Optional.empty(); } finally { this.lock.readLock().unlock(); } } @Override public int size() { this.lock.readLock().lock(); try { return doublyLinkedList.size(); } finally { this.lock.readLock().unlock(); } } @Override public boolean isEmpty() { return size() == 0; } @Override public void clear() { this.lock.writeLock().lock(); try { linkedListNodeMap.clear(); doublyLinkedList.clear(); } finally { this.lock.writeLock().unlock(); } } private boolean evictElement() { this.lock.writeLock().lock(); try { LinkedListNode<CacheElement<K, V>> linkedListNode = doublyLinkedList.removeTail(); if (linkedListNode.isEmpty()) { return false; } linkedListNodeMap.remove(linkedListNode.getElement().getKey()); return true; } finally { this.lock.writeLock().unlock(); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/Cache.java
data-structures/src/main/java/com/baeldung/lrucache/Cache.java
package com.baeldung.lrucache; import java.util.Optional; public interface Cache<K, V> { boolean put(K key, V value); Optional<V> get(K key); int size(); boolean isEmpty(); void clear(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/DoublyLinkedList.java
data-structures/src/main/java/com/baeldung/lrucache/DoublyLinkedList.java
package com.baeldung.lrucache; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; public class DoublyLinkedList<T> { private DummyNode<T> dummyNode; private LinkedListNode<T> head; private LinkedListNode<T> tail; private AtomicInteger size; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public DoublyLinkedList() { this.dummyNode = new DummyNode<T>(this); clear(); } public void clear() { this.lock.writeLock().lock(); try { head = dummyNode; tail = dummyNode; size = new AtomicInteger(0); } finally { this.lock.writeLock().unlock(); } } public int size() { this.lock.readLock().lock(); try { return size.get(); } finally { this.lock.readLock().unlock(); } } public boolean isEmpty() { this.lock.readLock().lock(); try { return head.isEmpty(); } finally { this.lock.readLock().unlock(); } } public boolean contains(T value) { this.lock.readLock().lock(); try { return search(value).hasElement(); } finally { this.lock.readLock().unlock(); } } public LinkedListNode<T> search(T value) { this.lock.readLock().lock(); try { return head.search(value); } finally { this.lock.readLock().unlock(); } } public LinkedListNode<T> add(T value) { this.lock.writeLock().lock(); try { head = new Node<T>(value, head, this); if (tail.isEmpty()) { tail = head; } size.incrementAndGet(); return head; } finally { this.lock.writeLock().unlock(); } } public boolean addAll(Collection<T> values) { this.lock.writeLock().lock(); try { for (T value : values) { if (add(value).isEmpty()) { return false; } } return true; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> remove(T value) { this.lock.writeLock().lock(); try { LinkedListNode<T> linkedListNode = head.search(value); if (!linkedListNode.isEmpty()) { if (linkedListNode == tail) { tail = tail.getPrev(); } if (linkedListNode == head) { head = head.getNext(); } linkedListNode.detach(); size.decrementAndGet(); } return linkedListNode; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> removeTail() { this.lock.writeLock().lock(); try { LinkedListNode<T> oldTail = tail; if (oldTail == head) { tail = head = dummyNode; } else { tail = tail.getPrev(); oldTail.detach(); } if (!oldTail.isEmpty()) { size.decrementAndGet(); } return oldTail; } finally { this.lock.writeLock().unlock(); } } public LinkedListNode<T> moveToFront(LinkedListNode<T> node) { return node.isEmpty() ? dummyNode : updateAndMoveToFront(node, node.getElement()); } public LinkedListNode<T> updateAndMoveToFront(LinkedListNode<T> node, T newValue) { this.lock.writeLock().lock(); try { if (node.isEmpty() || (this != (node.getListReference()))) { return dummyNode; } detach(node); add(newValue); return head; } finally { this.lock.writeLock().unlock(); } } private void detach(LinkedListNode<T> node) { if (node != tail) { node.detach(); if (node == head) { head = head.getNext(); } size.decrementAndGet(); } else { removeTail(); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/CacheElement.java
data-structures/src/main/java/com/baeldung/lrucache/CacheElement.java
package com.baeldung.lrucache; /** * Created by arash on 09.07.21. */ public class CacheElement<K,V> { private K key; private V value; public CacheElement(K key, V value) { this.value = value; this.key = key; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/lrucache/LinkedListNode.java
data-structures/src/main/java/com/baeldung/lrucache/LinkedListNode.java
package com.baeldung.lrucache; public interface LinkedListNode<V> { boolean hasElement(); boolean isEmpty(); V getElement() throws NullPointerException; void detach(); DoublyLinkedList<V> getListReference(); LinkedListNode<V> setPrev(LinkedListNode<V> prev); LinkedListNode<V> setNext(LinkedListNode<V> next); LinkedListNode<V> getPrev(); LinkedListNode<V> getNext(); LinkedListNode<V> search(V value); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
package com.baeldung.tree; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class BinaryTree { Node root; public void add(int value) { root = addRecursive(root, value); } private Node addRecursive(Node current, int value) { if (current == null) { return new Node(value); } if (value < current.value) { current.left = addRecursive(current.left, value); } else if (value > current.value) { current.right = addRecursive(current.right, value); } return current; } public boolean isEmpty() { return root == null; } public int getSize() { return getSizeRecursive(root); } private int getSizeRecursive(Node current) { return current == null ? 0 : getSizeRecursive(current.left) + 1 + getSizeRecursive(current.right); } public boolean containsNode(int value) { return containsNodeRecursive(root, value); } private boolean containsNodeRecursive(Node current, int value) { if (current == null) { return false; } if (value == current.value) { return true; } return value < current.value ? containsNodeRecursive(current.left, value) : containsNodeRecursive(current.right, value); } public void delete(int value) { root = deleteRecursive(root, value); } private Node deleteRecursive(Node current, int value) { if (current == null) { return null; } if (value == current.value) { // Case 1: no children if (current.left == null && current.right == null) { return null; } // Case 2: only 1 child if (current.right == null) { return current.left; } if (current.left == null) { return current.right; } // Case 3: 2 children int smallestValue = findSmallestValue(current.right); current.value = smallestValue; current.right = deleteRecursive(current.right, smallestValue); return current; } if (value < current.value) { current.left = deleteRecursive(current.left, value); return current; } current.right = deleteRecursive(current.right, value); return current; } private int findSmallestValue(Node root) { return root.left == null ? root.value : findSmallestValue(root.left); } public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); visit(node.value); traverseInOrder(node.right); } } public void traversePreOrder(Node node) { if (node != null) { visit(node.value); traversePreOrder(node.left); traversePreOrder(node.right); } } public void traversePostOrder(Node node) { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); visit(node.value); } } public void traverseLevelOrder() { if (root == null) { return; } Queue<Node> nodes = new LinkedList<>(); nodes.add(root); while (!nodes.isEmpty()) { Node node = nodes.remove(); System.out.print(" " + node.value); if (node.left != null) { nodes.add(node.left); } if (node.right != null) { nodes.add(node.right); } } } public void traverseInOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current = root; while (current != null || !stack.isEmpty()) { while (current != null) { stack.push(current); current = current.left; } Node top = stack.pop(); visit(top.value); current = top.right; } } public void traversePreOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current = root; stack.push(root); while (current != null && !stack.isEmpty()) { current = stack.pop(); visit(current.value); if (current.right != null) stack.push(current.right); if (current.left != null) stack.push(current.left); } } public void traversePostOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node prev = root; Node current = root; stack.push(root); while (current != null && !stack.isEmpty()) { current = stack.peek(); boolean hasChild = (current.left != null || current.right != null); boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); if (!hasChild || isPrevLastChild) { current = stack.pop(); visit(current.value); prev = current; } else { if (current.right != null) { stack.push(current.right); } if (current.left != null) { stack.push(current.left); } } } } private void visit(int value) { System.out.print(" " + value); } class Node { int value; Node left; Node right; Node(int value) { this.value = value; right = null; left = null; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java
spring-structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java
package com.baeldung.structurizr; import com.structurizr.Workspace; import com.structurizr.analysis.ComponentFinder; import com.structurizr.analysis.ReferencedTypesSupportingTypesStrategy; import com.structurizr.analysis.SourceCodeComponentFinderStrategy; import com.structurizr.analysis.SpringComponentFinderStrategy; import com.structurizr.io.WorkspaceWriterException; import com.structurizr.io.plantuml.PlantUMLWriter; import com.structurizr.model.Component; import com.structurizr.model.Container; import com.structurizr.model.Model; import com.structurizr.model.Person; import com.structurizr.model.SoftwareSystem; import com.structurizr.model.Tags; import com.structurizr.view.ComponentView; import com.structurizr.view.ContainerView; import com.structurizr.view.Routing; import com.structurizr.view.Shape; import com.structurizr.view.Styles; import com.structurizr.view.SystemContextView; import com.structurizr.view.View; import com.structurizr.view.ViewSet; import java.io.File; import java.io.StringWriter; import java.util.HashSet; import java.util.Set; public class StructurizrSimple { public static final String PAYMENT_TERMINAL = "Payment Terminal"; public static final String FRAUD_DETECTOR = "Fraud Detector"; public static final String SOFTWARE_SYSTEM_VIEW = "SoftwareSystemView"; public static final String CONTAINER_VIEW = "ContainerView"; public static final String COMPONENT_VIEW = "ComponentView"; public static final String JVM2_COMPONENT_VIEW = "JVM2ComponentView"; public static void main(String[] args) throws Exception { Workspace workspace = getSoftwareSystem(); addContainers(workspace); addComponents(workspace); addSpringComponents(workspace); exportToPlantUml(findViewWithKey(workspace.getViews(), SOFTWARE_SYSTEM_VIEW)); exportToPlantUml(findViewWithKey(workspace.getViews(), CONTAINER_VIEW)); exportToPlantUml(findViewWithKey(workspace.getViews(), COMPONENT_VIEW)); exportToPlantUml(findViewWithKey(workspace.getViews(), JVM2_COMPONENT_VIEW)); addStyles(workspace.getViews()); //uploadToExternal(workspace); } private static View findViewWithKey(ViewSet viewSet, String key) { if (key == null) { throw new IllegalArgumentException("A key must be specified."); } Set<View> views = new HashSet<>(); views.addAll(viewSet.getSystemLandscapeViews()); views.addAll(viewSet.getSystemContextViews()); views.addAll(viewSet.getContainerViews()); views.addAll(viewSet.getComponentViews()); views.addAll(viewSet.getDynamicViews()); views.addAll(viewSet.getDeploymentViews()); return views.stream().filter(v -> key.equals(v.getKey())).findFirst().orElse(null); } private static void addSpringComponents(Workspace workspace) throws Exception { Container jvm2 = workspace.getModel().getSoftwareSystemWithName(PAYMENT_TERMINAL).getContainerWithName("JVM-2"); findComponents(jvm2); ComponentView view = workspace.getViews().createComponentView(jvm2, JVM2_COMPONENT_VIEW, "JVM2ComponentView"); view.addAllComponents(); } private static void findComponents(Container jvm) throws Exception { ComponentFinder componentFinder = new ComponentFinder( jvm, "com.baeldung.structurizr", new SpringComponentFinderStrategy( new ReferencedTypesSupportingTypesStrategy() ), new SourceCodeComponentFinderStrategy(new File("."), 150)); componentFinder.findComponents(); } private static void addComponents(Workspace workspace) { Model model = workspace.getModel(); SoftwareSystem paymentTerminal = model.getSoftwareSystemWithName(PAYMENT_TERMINAL); Container jvm1 = paymentTerminal.getContainerWithName("JVM-1"); Component jaxrs = jvm1.addComponent("jaxrs-jersey", "restful webservice implementation", "rest"); Component gemfire = jvm1.addComponent("gemfire", "Clustered Cache Gemfire", "cache"); Component hibernate = jvm1.addComponent("hibernate", "Data Access Layer", "jpa"); jaxrs.uses(gemfire, ""); gemfire.uses(hibernate, ""); ComponentView componentView = workspace.getViews().createComponentView(jvm1, COMPONENT_VIEW, "JVM Components"); componentView.addAllComponents(); } private static void addContainers(Workspace workspace) { Model model = workspace.getModel(); SoftwareSystem paymentTerminal = model.getSoftwareSystemWithName(PAYMENT_TERMINAL); Container f5 = paymentTerminal.addContainer("Payment Load Balancer", "Payment Load Balancer", "F5"); Container jvm1 = paymentTerminal.addContainer("JVM-1", "JVM-1", "Java Virtual Machine"); Container jvm2 = paymentTerminal.addContainer("JVM-2", "JVM-2", "Java Virtual Machine"); Container jvm3 = paymentTerminal.addContainer("JVM-3", "JVM-3", "Java Virtual Machine"); Container oracle = paymentTerminal.addContainer("oracleDB", "Oracle Database", "RDBMS"); f5.uses(jvm1, "route"); f5.uses(jvm2, "route"); f5.uses(jvm3, "route"); jvm1.uses(oracle, "storage"); jvm2.uses(oracle, "storage"); jvm3.uses(oracle, "storage"); ContainerView view = workspace.getViews().createContainerView(paymentTerminal, CONTAINER_VIEW, "Container View"); view.addAllContainers(); } private static void exportToPlantUml(View view) throws WorkspaceWriterException { StringWriter stringWriter = new StringWriter(); PlantUMLWriter plantUMLWriter = new PlantUMLWriter(); plantUMLWriter.write(view, stringWriter); System.out.println(stringWriter.toString()); } private static Workspace getSoftwareSystem() { Workspace workspace = new Workspace("Payment Gateway", "Payment Gateway"); Model model = workspace.getModel(); Person user = model.addPerson("Merchant", "Merchant"); SoftwareSystem paymentTerminal = model.addSoftwareSystem(PAYMENT_TERMINAL, "Payment Terminal"); user.uses(paymentTerminal, "Makes payment"); SoftwareSystem fraudDetector = model.addSoftwareSystem(FRAUD_DETECTOR, "Fraud Detector"); paymentTerminal.uses(fraudDetector, "Obtains fraud score"); ViewSet viewSet = workspace.getViews(); SystemContextView contextView = viewSet.createSystemContextView(workspace.getModel().getSoftwareSystemWithName(PAYMENT_TERMINAL), SOFTWARE_SYSTEM_VIEW, "Payment Gateway Diagram"); contextView.addAllElements(); return workspace; } private static void addStyles(ViewSet viewSet) { Styles styles = viewSet.getConfiguration().getStyles(); styles.addElementStyle(Tags.ELEMENT).color("#000000"); styles.addElementStyle(Tags.PERSON).background("#ffbf00").shape(Shape.Person); styles.addElementStyle(Tags.CONTAINER).background("#facc2E"); styles.addRelationshipStyle(Tags.RELATIONSHIP).routing(Routing.Orthogonal); styles.addRelationshipStyle(Tags.ASYNCHRONOUS).dashed(true); styles.addRelationshipStyle(Tags.SYNCHRONOUS).dashed(false); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-structurizr/src/main/java/com/baeldung/structurizr/spring/GenericComponent.java
spring-structurizr/src/main/java/com/baeldung/structurizr/spring/GenericComponent.java
package com.baeldung.structurizr.spring; import org.springframework.stereotype.Component; @Component public class GenericComponent { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-structurizr/src/main/java/com/baeldung/structurizr/spring/PaymentRepository.java
spring-structurizr/src/main/java/com/baeldung/structurizr/spring/PaymentRepository.java
package com.baeldung.structurizr.spring; import org.springframework.stereotype.Repository; @Repository public class PaymentRepository { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-structurizr/src/main/java/com/baeldung/structurizr/spring/PaymentController.java
spring-structurizr/src/main/java/com/baeldung/structurizr/spring/PaymentController.java
package com.baeldung.structurizr.spring; import org.springframework.stereotype.Controller; import javax.annotation.Resource; @Controller public class PaymentController { @Resource private PaymentRepository repository; @Resource private GenericComponent component; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/twoanglesdifference/AngleDifferenceCalculatorTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/twoanglesdifference/AngleDifferenceCalculatorTest.java
/** * Package to host JUnit Test code for AngleDifferenceCalculator Class */ package com.baeldung.algorithms.twoanglesdifference; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class AngleDifferenceCalculatorTest { private static final double EPSILON = 0.0001; @Test void whenNormalizingAngle_thenReturnsCorrectRange() { assertEquals(90, AngleDifferenceCalculator.normalizeAngle(450), EPSILON); assertEquals(30, AngleDifferenceCalculator.normalizeAngle(390), EPSILON); assertEquals(330, AngleDifferenceCalculator.normalizeAngle(-30), EPSILON); assertEquals(0, AngleDifferenceCalculator.normalizeAngle(360), EPSILON); } @Test void whenCalculatingAbsoluteDifference_thenReturnsCorrectValue() { assertEquals(100, AngleDifferenceCalculator.absoluteDifference(10, 110), EPSILON); assertEquals(290, AngleDifferenceCalculator.absoluteDifference(10, 300), EPSILON); assertEquals(30, AngleDifferenceCalculator.absoluteDifference(-30, 0), EPSILON); } @Test void whenCalculatingShortestDifference_thenReturnsCorrectValue() { assertEquals(100, AngleDifferenceCalculator.shortestDifference(10, 110), EPSILON); assertEquals(70, AngleDifferenceCalculator.shortestDifference(10, 300), EPSILON); assertEquals(30, AngleDifferenceCalculator.shortestDifference(-30, 0), EPSILON); assertEquals(0, AngleDifferenceCalculator.shortestDifference(360, 0), EPSILON); } @Test void whenCalculatingSignedShortestDifference_thenReturnsCorrectValue() { assertEquals(100, AngleDifferenceCalculator.signedShortestDifference(10, 110), EPSILON); assertEquals(-70, AngleDifferenceCalculator.signedShortestDifference(10, 300), EPSILON); assertEquals(30, AngleDifferenceCalculator.signedShortestDifference(-30, 0), EPSILON); assertEquals(70, AngleDifferenceCalculator.signedShortestDifference(300, 10), EPSILON); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/palindrome/PalindromeUnitTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/palindrome/PalindromeUnitTest.java
package com.baeldung.algorithms.palindrome; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class PalindromeUnitTest { @Test void givenNumber_whenUsingIterativeApproach_thenCheckPalindrome() { assertTrue(PalindromeNumber.isPalindromeIterative(12321)); assertFalse(PalindromeNumber.isPalindromeIterative(123)); assertTrue(PalindromeNumber.isPalindromeIterative(123321)); assertFalse(PalindromeNumber.isPalindromeIterative(1234)); } @Test void givenNumber_whenUsingStringApproach_thenCheckPalindrome() { assertTrue(PalindromeNumber.isPalindromeString(12321)); assertFalse(PalindromeNumber.isPalindromeString(123)); assertTrue(PalindromeNumber.isPalindromeString(123321)); assertFalse(PalindromeNumber.isPalindromeString(1234)); } @Test void givenNumber_whenUsingRecursiveApproach_thenCheckPalindrome() { assertTrue(PalindromeNumber.isPalindromeRecursive(12321)); assertFalse(PalindromeNumber.isPalindromeRecursive(123)); assertTrue(PalindromeNumber.isPalindromeRecursive(123321)); assertFalse(PalindromeNumber.isPalindromeRecursive(1234)); } @Test void givenNumber_whenUsingHalfReversalApproach_thenCheckPalindrome() { assertTrue(PalindromeNumber.isPalindromeHalfReversal(12321)); assertFalse(PalindromeNumber.isPalindromeHalfReversal(123)); assertTrue(PalindromeNumber.isPalindromeHalfReversal(123321)); assertFalse(PalindromeNumber.isPalindromeHalfReversal(1234)); } @Test void givenNumber_whenUsingDigitByDigitApproach_thenCheckPalindrome() { assertTrue(PalindromeNumber.isPalindromeDigitByDigit(12321)); assertFalse(PalindromeNumber.isPalindromeDigitByDigit(123)); assertTrue(PalindromeNumber.isPalindromeDigitByDigit(123321)); assertFalse(PalindromeNumber.isPalindromeDigitByDigit(1234)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/subarraysumzero/LargestSubarraySumZeroUnitTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/subarraysumzero/LargestSubarraySumZeroUnitTest.java
package com.baeldung.algorithms.subarraysumzero; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class LargestSubarraySumZeroUnitTest { @Test public void givenArray_whenUseTwoLoops_thenFindSubarrayWithSumZero() { int[] arr1 = { 4, -3, -6, 5, 1, 6, 8 }; int[] arr2 = { 15, -2, 2, -8, 1, 7, 10, 23 }; int[] arr3 = { -3, 2, 3, 1, 6 }; assertEquals(4, LargestSubarraySumZero.maxLenBruteForce(arr1)); assertEquals(5, LargestSubarraySumZero.maxLenBruteForce(arr2)); assertEquals(0, LargestSubarraySumZero.maxLenBruteForce(arr3)); } @Test public void givenArray_whenUseHashmap_thenFindSubarrayWithSumZero() { int[] arr1 = { 4, -3, -6, 5, 1, 6, 8 }; int[] arr2 = { 15, -2, 2, -8, 1, 7, 10, 23 }; int[] arr3 = { -3, 2, 3, 1, 6 }; assertEquals(4, LargestSubarraySumZero.maxLenHashMap(arr1)); assertEquals(5, LargestSubarraySumZero.maxLenHashMap(arr2)); assertEquals(0, LargestSubarraySumZero.maxLenHashMap(arr3)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/perfectnumber/PerfectNumberUnitTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/perfectnumber/PerfectNumberUnitTest.java
package com.baeldung.algorithms.perfectnumber; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class PerfectNumberUnitTest { @Test void givenPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnTrue() { assertTrue(PerfectNumber.isPerfectBruteForce(6)); } @Test void givenNonPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectBruteForce(10)); } @Test void givenNegativeNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectBruteForce(-28)); } @Test void givenPerfectNumber_whenCheckingIsPerfectStream_thenReturnTrue() { assertTrue(PerfectNumber.isPerfectStream(28)); } @Test void givenNonPerfectNumber_whenCheckingIsPerfectStream_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectStream(10)); } @Test void givenNegativeNumber_whenCheckingIsPerfectStream_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectStream(-6)); } @Test void givenPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnTrue() { assertTrue(PerfectNumber.isPerfectEuclidEuler(28)); } @Test void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectEuclidEuler(10)); } @Test void givenNegativeNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectEuclidEuler(-6)); } @Test void givenPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnTrue() { assertTrue(PerfectNumber.isPerfectEuclidEulerUsingShift(28)); } @Test void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(10)); } @Test void givenNegativeNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() { assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(-6)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/cosinesimilarity/CosineSimilarityUnitTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/cosinesimilarity/CosineSimilarityUnitTest.java
package com.baeldung.algorithms.cosinesimilarity; import org.junit.jupiter.api.Test; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.impl.reduce3.CosineSimilarity; import org.nd4j.linalg.factory.Nd4j; import java.util.Arrays; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; public class CosineSimilarityUnitTest { static final double[] VECTOR_A = {3, 4}; static final double[] VECTOR_B = {5, 12}; static final double EXPECTED_SIMILARITY = 0.9692307692307692; static double calculateCosineSimilarity(double[] vectorA, double[] vectorB) { if (vectorA == null || vectorB == null || vectorA.length != vectorB.length || vectorA.length == 0) { throw new IllegalArgumentException("Vectors must be non-null, non-empty, and of the same length."); } double dotProduct = 0.0; double magnitudeA = 0.0; double magnitudeB = 0.0; for (int i = 0; i < vectorA.length; i++) { dotProduct += vectorA[i] * vectorB[i]; magnitudeA += vectorA[i] * vectorA[i]; magnitudeB += vectorB[i] * vectorB[i]; } double finalMagnitudeA = Math.sqrt(magnitudeA); double finalMagnitudeB = Math.sqrt(magnitudeB); if (finalMagnitudeA == 0.0 || finalMagnitudeB == 0.0) { return 0.0; } return dotProduct / (finalMagnitudeA * finalMagnitudeB); } public static double calculateCosineSimilarityWithStreams(double[] vectorA, double[] vectorB) { if (vectorA == null || vectorB == null || vectorA.length != vectorB.length || vectorA.length == 0) { throw new IllegalArgumentException("Vectors must be non-null, non-empty, and of the same length."); } double dotProduct = IntStream.range(0, vectorA.length).mapToDouble(i -> vectorA[i] * vectorB[i]).sum(); double magnitudeA = Arrays.stream(vectorA).map(v -> v * v).sum(); double magnitudeB = IntStream.range(0, vectorA.length).mapToDouble(i -> vectorB[i] * vectorB[i]).sum(); double finalMagnitudeA = Math.sqrt(magnitudeA); double finalMagnitudeB = Math.sqrt(magnitudeB); if (finalMagnitudeA == 0.0 || finalMagnitudeB == 0.0) { return 0.0; } return dotProduct / (finalMagnitudeA * finalMagnitudeB); } @Test void givenTwoHighlySimilarVectors_whenCalculatedNatively_thenReturnsHighSimilarityScore() { double actualSimilarity = calculateCosineSimilarity(VECTOR_A, VECTOR_B); assertEquals(EXPECTED_SIMILARITY, actualSimilarity, 1e-15); } @Test void givenTwoHighlySimilarVectors_whenCalculatedNativelyWithStreams_thenReturnsHighSimilarityScore() { double actualSimilarity = calculateCosineSimilarityWithStreams(VECTOR_A, VECTOR_B); assertEquals(EXPECTED_SIMILARITY, actualSimilarity, 1e-15); } @Test void givenTwoHighlySimilarVectors_whenCalculatedNativelyWithCommonsMath_thenReturnsHighSimilarityScore() { INDArray vec1 = Nd4j.create(VECTOR_A); INDArray vec2 = Nd4j.create(VECTOR_B); CosineSimilarity cosSim = new CosineSimilarity(vec1, vec2); double actualSimilarity = Nd4j.getExecutioner().exec(cosSim).getDouble(0); assertEquals(EXPECTED_SIMILARITY, actualSimilarity, 1e-15); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/sumoftwosquares/NumberAsSumOfTwoSquaresUnitTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/sumoftwosquares/NumberAsSumOfTwoSquaresUnitTest.java
package com.baeldung.algorithms.sumoftwosquares; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.DisplayName; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; class NumberAsSumOfTwoSquaresUnitTest { @Test @DisplayName("Given input number can be expressed as a sum of squares, when checked, then returns true") void givenNumberIsSumOfSquares_whenCheckIsCalled_thenReturnsTrue() { // Simple cases assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(0)); // 0^2 + 0^2 assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(1)); // 1^2 + 0^2 assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(5)); // 1^2 + 2^2 assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(8)); // 2^2 + 2^2 // Cases from Fermat theorem assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(50)); // 2 * 5^2. No 4k+3 primes. assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(45)); // 3^2 * 5. 4k+3 prime (3) has even exp. assertTrue(NumberAsSumOfTwoSquares.isSumOfTwoSquares(18)); // 2 * 3^2. 4k+3 prime (3) has even exp. } @Test @DisplayName("Given input number can't be expressed as a sum of squares, when checked, then returns false") void givenNumberIsNotSumOfSquares_whenCheckIsCalled_thenReturnsFalse() { // Simple cases assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(3)); // 3 (4k+3, exp 1) assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(6)); // 2 * 3 (3 has exp 1) assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(7)); // 7 (4k+3, exp 1) assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(11)); // 11 (4k+3, exp 1) // Cases from theorem assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(12)); // 2^2 * 3 (3 has exp 1) assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(21)); // 3 * 7 (both 3 and 7 have exp 1) assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(28)); // 2^2 * 7 (7 has exp 1) } @Test @DisplayName("Given input number is negative, when checked, then returns false") void givenNegativeNumber_whenCheckIsCalled_thenReturnsFalse() { assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(-1)); // Negatives as hygiene assertFalse(NumberAsSumOfTwoSquares.isSumOfTwoSquares(-10)); // Negatives as hygiene } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/bcdtodecimal/BCDtoDecimalConverterTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/bcdtodecimal/BCDtoDecimalConverterTest.java
package com.baeldung.algorithms.bcdtodecimal; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class BCDtoDecimalConverterTest { // 1. Tests for convertPackedByte(byte bcdByte) @Test void testConvertPackedByteValidValues() { // Test 05 (0x05) -> assertEquals(5, BCDtoDecimalConverter.convertPackedByte((byte) 0x05)); // Test 22 (0x22) -> 22 assertEquals(22, BCDtoDecimalConverter.convertPackedByte((byte) 0x22)); // Test 97 (0x97) -> 97 assertEquals(97, BCDtoDecimalConverter.convertPackedByte((byte) 0x097)); } @Test void testConvertPackedByteInvalidUpperNibbleThrowsException() { // Test Upper nibble is A (1010), Lower nibble is 1 (0001) -> 0xA1 byte invalidByte = (byte) 0xA1; assertThrows(IllegalArgumentException.class, () -> BCDtoDecimalConverter.convertPackedByte(invalidByte), "Received non-BCD upper nibble (A). Provide valid BCD nibbles (0-9)."); } @Test void testConvertPackedByteBothInvalidThrowsException() { // test Upper nibble is B, Lower nibble is E -> 0xBE byte invalidByte = (byte) 0xBE; assertThrows(IllegalArgumentException.class, () -> BCDtoDecimalConverter.convertPackedByte(invalidByte), "Received both nibbles as non-BCD. Provide valid BCD nibbles (0-9)." ); } // ------------------------------------------------------------------------- // 2. Tests for convertPackedByteArray(byte[] bcdArray) @Test void testConvertPackedByteArrayValidValues() { // Test 0 -> [0x00] assertEquals(0L, BCDtoDecimalConverter.convertPackedByteArray(new byte[]{(byte) 0x00})); // Test 99 -> [0x99] assertEquals(99L, BCDtoDecimalConverter.convertPackedByteArray(new byte[]{(byte) 0x99})); // Test 1234 -> [0x12, 0x34] byte[] bcd1234 = {(byte) 0x12, (byte) 0x34}; assertEquals(1234L, BCDtoDecimalConverter.convertPackedByteArray(bcd1234)); // Test 12345678 -> [0x12, 0x34, 0x56, 0x78] byte[] bcdLarge = {(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78}; assertEquals(12345678L, BCDtoDecimalConverter.convertPackedByteArray(bcdLarge)); } @Test void testConvertPackedByteArrayEmptyArray() { // Test empty array -> 0 assertEquals(0L, BCDtoDecimalConverter.convertPackedByteArray(new byte[]{})); } @Test void testConvertPackedByteArrayMaximumSafeLong() { // Test a large number that fits within a long (18 digits) // 999,999,999,999,999,999 (18 nines) byte[] bcdMax = {(byte) 0x99, (byte) 0x99, (byte) 0x99, (byte) 0x99, (byte) 0x99, (byte) 0x99, (byte) 0x99, (byte) 0x99, (byte) 0x99}; assertEquals(999999999999999999L, BCDtoDecimalConverter.convertPackedByteArray(bcdMax)); } @Test void testConvertPackedByteArrayInvalidNibbleThrowsException() { // Contains 0x1A (A is an invalid BCD digit) byte[] bcdInvalid = {(byte) 0x12, (byte) 0x1A, (byte) 0x34}; assertThrows(IllegalArgumentException.class, () -> BCDtoDecimalConverter.convertPackedByteArray(bcdInvalid), "Received array containing an invalid BCD byte. Provide valid BCD nibbles (0-9)." ); } @Test void testConvertPackedByteArray_InvalidFirstByteThrowsException() { // Invalid BCD byte at the start byte[] bcdInvalid = {(byte) 0xF0, (byte) 0x12}; assertThrows(IllegalArgumentException.class, () -> BCDtoDecimalConverter.convertPackedByteArray(bcdInvalid), "Received first byte as an invalid BCD byte. Provide valid BCD nibbles (0-9)." ); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/consecutivenumbers/ConsecutiveNumbersUnitTest.java
algorithms-modules/algorithms-numeric/src/test/java/com/baeldung/algorithms/consecutivenumbers/ConsecutiveNumbersUnitTest.java
package com.baeldung.algorithms.consecutivenumbers; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class ConsecutiveNumbersUnitTest { @Test void whenIsSumOfConsecutiveUsingBruteForce_thenReturnsTrue() { int n = 15; boolean isSumOfConsecutive = false; for (int k = 2; (k * (k - 1)) / 2 < n; k++) { int diff = n - k * (k - 1) / 2; if (diff % k == 0 && diff / k > 0) { isSumOfConsecutive = true; break; } } assertTrue(isSumOfConsecutive); } @Test void whenIsSumOfConsecutiveUsingBitwise_thenReturnsTrue() { int n = 15; boolean result = (n > 0) && ((n & (n - 1)) != 0); assertTrue(result); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/twoanglesdifference/AngleDifferenceCalculator.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/twoanglesdifference/AngleDifferenceCalculator.java
/** * Package to host code for calculating three types of angle difference */ package com.baeldung.algorithms.twoanglesdifference; public class AngleDifferenceCalculator { /** * Normalizes an angle to be within the range [0, 360). * * @param angle The angle in degrees. * @return The normalized angle. */ public static double normalizeAngle(double angle) { return (angle % 360 + 360) % 360; } /** * Calculates the absolute difference between two angles. * * @param angle1 The first angle in degrees. * @param angle2 The second angle in degrees. * @return The absolute difference in degrees. */ public static double absoluteDifference(double angle1, double angle2) { return Math.abs(angle1 - angle2); } /** * Calculates the shortest difference between two angles. * * @param angle1 The first angle in degrees. * @param angle2 The second angle in degrees. * @return The shortest difference in degrees (0 to 180). */ public static double shortestDifference(double angle1, double angle2) { double diff = absoluteDifference(normalizeAngle(angle1), normalizeAngle(angle2)); return Math.min(diff, 360 - diff); } /** * Calculates the signed shortest difference between two angles. * A positive result indicates counter-clockwise rotation, a negative result indicates clockwise. * * @param angle1 The first angle in degrees. * @param angle2 The second angle in degrees. * @return The signed shortest difference in degrees (-180 to 180). */ public static double signedShortestDifference(double angle1, double angle2) { double normalizedAngle1 = normalizeAngle(angle1); double normalizedAngle2 = normalizeAngle(angle2); double diff = normalizedAngle2 - normalizedAngle1; if (diff > 180) { return diff - 360; } else if (diff < -180) { return diff + 360; } else { return diff; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/palindrome/PalindromeNumber.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/palindrome/PalindromeNumber.java
package com.baeldung.algorithms.palindrome; public class PalindromeNumber { public static boolean isPalindromeIterative(int number) { int originalNumber = number; int reversedNumber = 0; while (number > 0) { int digit = number % 10; reversedNumber = reversedNumber * 10 + digit; number /= 10; } return originalNumber == reversedNumber; } public static boolean isPalindromeString(int number) { String original = String.valueOf(number); String reversed = new StringBuilder(original).reverse() .toString(); return original.equals(reversed); } public static boolean isPalindromeRecursive(int number) { return isPalindromeHelper(number, 0) == number; } private static int isPalindromeHelper(int number, int reversedNumber) { if (number == 0) { return reversedNumber; } reversedNumber = reversedNumber * 10 + number % 10; return isPalindromeHelper(number / 10, reversedNumber); } public static boolean isPalindromeHalfReversal(int number) { if (number < 0 || (number % 10 == 0 && number != 0)) { return false; } int reversedNumber = 0; while (number > reversedNumber) { reversedNumber = reversedNumber * 10 + number % 10; number /= 10; } return number == reversedNumber || number == reversedNumber / 10; } public static boolean isPalindromeDigitByDigit(int number) { if (number < 0) { return false; } int divisor = 1; while (number / divisor >= 10) { divisor *= 10; } while (number != 0) { int leading = number / divisor; int trailing = number % 10; if (leading != trailing) { return false; } number = (number % divisor) / 10; divisor /= 100; } return true; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/subarraysumzero/LargestSubarraySumZero.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/subarraysumzero/LargestSubarraySumZero.java
package com.baeldung.algorithms.subarraysumzero; import java.util.HashMap; public class LargestSubarraySumZero { public static int maxLenBruteForce(int[] arr) { int maxLength = 0; for (int i = 0; i < arr.length; i++) { int sum = 0; for (int j = i; j < arr.length; j++) { sum += arr[j]; if (sum == 0) { maxLength = Math.max(maxLength, j - i + 1); } } } return maxLength; } public static int maxLenHashMap(int[] arr) { HashMap<Integer, Integer> map = new HashMap<>(); int sum = 0; int maxLength = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; if (sum == 0) { maxLength = i + 1; } if (map.containsKey(sum)) { maxLength = Math.max(maxLength, i - map.get(sum)); } else { map.put(sum, i); } } return maxLength; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/perfectnumber/PerfectNumberBenchmark.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/perfectnumber/PerfectNumberBenchmark.java
package com.baeldung.algorithms.perfectnumber; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; @State(Scope.Benchmark) public class PerfectNumberBenchmark { @Benchmark public boolean bruteForceBenchmark() { return PerfectNumber.isPerfectBruteForce(33550336); } @Benchmark public boolean streamBenchmark() { return PerfectNumber.isPerfectStream(33550336); } @Benchmark public boolean euclidEulerBenchmark() { return PerfectNumber.isPerfectEuclidEuler(33550336); } @Benchmark public boolean euclidEulerUsingShiftBenchmark() { return PerfectNumber.isPerfectEuclidEulerUsingShift(33550336); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(PerfectNumberBenchmark.class.getSimpleName()) .forks(1) .build(); new Runner(options).run(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/perfectnumber/PerfectNumber.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/perfectnumber/PerfectNumber.java
package com.baeldung.algorithms.perfectnumber; import java.util.stream.IntStream; class PerfectNumber { public static boolean isPerfectBruteForce(int number) { int sum = 0; for (int i = 1; i <= number / 2; i++) { if (number % i == 0) { sum += i; } } return sum == number; } public static boolean isPerfectStream(int number) { int sum = IntStream.rangeClosed(2, (int) Math.sqrt(number)) .filter(test -> number % test == 0) .reduce(1, (s, test) -> s + test + (number / test)); return sum == number; } public static boolean isPerfectEuclidEuler(int number) { int p = 2; int perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1)); while (perfectNumber <= number) { if (perfectNumber == number) { return true; } p++; perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1)); } return false; } public static boolean isPerfectEuclidEulerUsingShift(int number) { int p = 2; int perfectNumber = (2 << (p - 1)) * ((2 << p) - 1); while (perfectNumber <= number) { if (perfectNumber == number) { return true; } p++; perfectNumber = (2 << (p - 1)) * ((2 << p) - 1); } return false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/sumoftwosquares/NumberAsSumOfTwoSquares.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/sumoftwosquares/NumberAsSumOfTwoSquares.java
package com.baeldung.algorithms.sumoftwosquares; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NumberAsSumOfTwoSquares { private static final Logger LOGGER = LoggerFactory.getLogger(NumberAsSumOfTwoSquares.class); /** * Checks if a non-negative integer n can be written as the * sum of two squares i.e. (a^2 + b^2) * This implementation is based on Fermat's theorem on sums of two squares. * * @param n The number to check (must be non-negative). * @return true if n can be written as a sum of two squares, false otherwise. */ public static boolean isSumOfTwoSquares(int n) { if (n < 0) { LOGGER.warn("Input must be non-negative. Returning false for n = {}", n); return false; } if (n == 0) { return true; // 0 = 0^2 + 0^2 } // 1. Reduce n to an odd number if n is even. while (n % 2 == 0) { n /= 2; } // 2. Iterate through odd prime factors starting from 3 for (int i = 3; i * i <= n; i += 2) { // 2a. Find the exponent of the factor i int count = 0; while (n % i == 0) { count++; n /= i; } // 2b. Check the condition from Fermat's theorem // If i is of form 4k+3 (i % 4 == 3) and has an odd exponent if (i % 4 == 3 && count % 2 != 0) { LOGGER.debug("Failing condition: factor {} (form 4k+3) has odd exponent {}", i, count); return false; } } // 3. Handle the last remaining factor (which is prime if > 1) // If n itself is a prime of the form 4k+3, its exponent is 1 (odd). if (n % 4 == 3) { LOGGER.debug("Failing condition: remaining factor {} is of form 4k+3", n); return false; } // 4. All 4k+3 primes had even exponents. return true; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/bcdtodecimal/BCDtoDecimalConverter.java
algorithms-modules/algorithms-numeric/src/main/java/com/baeldung/algorithms/bcdtodecimal/BCDtoDecimalConverter.java
package com.baeldung.algorithms.bcdtodecimal; public class BCDtoDecimalConverter { /** * Converts a single packed BCD byte to an integer. * Each byte represents two decimal digits. * * @param bcdByte The BCD byte to convert. * @return The decimal integer value. * @throws IllegalArgumentException if any nibble contains a non-BCD value (>9). */ public static int convertPackedByte(byte bcdByte) { int resultDecimal; int upperNibble = (bcdByte >> 4) & 0x0F; int lowerNibble = bcdByte & 0x0F; if (upperNibble > 9 || lowerNibble > 9) { throw new IllegalArgumentException( String.format("Invalid BCD format: byte 0x%02X contains non-decimal digit.", bcdByte) ); } resultDecimal = upperNibble * 10 + lowerNibble; return resultDecimal; } /** * Converts a BCD byte array to a long decimal value. * Each byte in the array iis mapped to a packed BCD byte, * representing two BCD nibbles. * * @param bcdArray The array of BCD bytes. * @return The combined long decimal value. * @throws IllegalArgumentException if any nibble contains a non-BCD value (>9). */ public static long convertPackedByteArray(byte[] bcdArray) { long resultDecimal = 0; for (byte bcd : bcdArray) { int upperNibble = (bcd >> 4) & 0x0F; int lowerNibble = bcd & 0x0F; if (upperNibble > 9 || lowerNibble > 9) { throw new IllegalArgumentException("Invalid BCD format: nibble contains non-decimal digit."); } resultDecimal = resultDecimal * 100 + (upperNibble * 10 + lowerNibble); } return resultDecimal; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { @ParameterizedTest @MethodSource("getLists") void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) { assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { @ParameterizedTest @MethodSource("getLists") void givenList_detectLoop(Node<Integer> head, boolean cycleExists) { assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { @ParameterizedTest @MethodSource("getLists") void givenList_detectLoop(Node<Integer> head, boolean cycleExists) { assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { @ParameterizedTest @MethodSource("getLists") void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) { assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java
package com.baeldung.algorithms.linkedlist; import java.util.Arrays; import java.util.Collection; import org.junit.runners.Parameterized.Parameters; public class CycleDetectionTestBase { public static Collection<Object[]> getLists() { return Arrays.asList(new Object[][] { { createList(), false }, { createListWithLoop(), true }, { createListWithFullCycle(), true }, { createListWithSingleNodeInCycle(), true } }); } public static Node<Integer> createList() { Node<Integer> root = Node.createNewNode(10, null); for (int i = 9; i >= 1; --i) { Node<Integer> current = Node.createNewNode(i, root); root = current; } return root; } public static Node<Integer> createListWithLoop() { Node<Integer> node = createList(); createLoop(node); return node; } public static Node<Integer> createListWithFullCycle() { Node<Integer> head = createList(); Node<Integer> tail = Node.getTail(head); tail.next = head; return head; } public static Node<Integer> createListWithSingleNodeInCycle() { Node<Integer> head = createList(); Node<Integer> tail = Node.getTail(head); tail.next = tail; return head; } public static void createLoop(Node<Integer> root) { Node<Integer> tail = Node.getTail(root); Node<Integer> middle = root; for (int i = 1; i <= 4; i++) { middle = middle.next; } tail.next = middle; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { @ParameterizedTest @MethodSource("getLists") void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) { assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java
package com.baeldung.algorithms.linkedlist; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { @ParameterizedTest @MethodSource("getLists") void givenList_detectLoop(Node<Integer> head, boolean cycleExists) { assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java
package com.baeldung.algorithms.moneywords; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; class NumberWordConverterUnitTest { @Test void whenMoneyNegative_thenReturnInvalidInput() { assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13)); } @Test void whenZeroDollarsGiven_thenReturnEmptyString() { assertEquals("", NumberWordConverter.getMoneyIntoWords(0)); } @Test void whenOnlyDollarsGiven_thenReturnWords() { assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); } @Test void whenOnlyCentsGiven_thenReturnWords() { assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6)); } @Test void whenAlmostAMillioDollarsGiven_thenReturnWords() { String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999)); } @Test void whenThirtyMillionDollarsGiven_thenReturnWords() { String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978)); } @Test void whenTwoBillionDollarsGiven_thenReturnWords() { String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810)); } @Test void whenGivenDollarsAndCents_thenReturnWords() { String expectedResult = "nine hundred twenty four dollars and sixty cents"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6)); } @Test void whenOneDollarAndNoCents_thenReturnDollarSingular() { assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); } @Test void whenNoDollarsAndOneCent_thenReturnCentSingular() { assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01)); } @Test void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02)); } @Test void whenNoDollarsAndNinetyNineCents_thenReturnWords() { assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99)); } @Test void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959)); } @Test void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/sudoku/BacktrackingAlgoritmUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/sudoku/BacktrackingAlgoritmUnitTest.java
package com.baeldung.algorithms.sudoku; import org.junit.Assert; import org.junit.Test; public class BacktrackingAlgoritmUnitTest { private static final int[][] board = { {8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 3, 6, 0, 0, 0, 0, 0}, {0, 7, 0, 0, 9, 0, 2, 0, 0}, {0, 5, 0, 0, 0, 7, 0, 0, 0}, {0, 0, 0, 0, 4, 5, 7, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 3, 0}, {0, 0, 1, 0, 0, 0, 0, 6, 8}, {0, 0, 8, 5, 0, 0, 0, 1, 0}, {0, 9, 0, 0, 0, 0, 4, 0, 0} }; @Test public void testSudokuBacktrackingAlgorithm() { BacktrackingAlgorithm solver = new BacktrackingAlgorithm(); solver.solve(board); Assert.assertArrayEquals(board[0], new int[] {8,1,2,7,5,3,6,4,9}); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java
package com.baeldung.algorithms.astar.underground; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.baeldung.algorithms.astar.Graph; import com.baeldung.algorithms.astar.RouteFinder; import lombok.extern.slf4j.Slf4j; @Slf4j class RouteFinderIntegrationTest { private Graph<Station> underground; private RouteFinder<Station> routeFinder; @BeforeEach public void setUp() throws Exception { Set<Station> stations = new HashSet<>(); Map<String, Set<String>> connections = new HashMap<>(); stations.add(new Station("1", "Acton Town", 51.5028, -0.2801)); stations.add(new Station("2", "Aldgate", 51.5143, -0.0755)); stations.add(new Station("3", "Aldgate East", 51.5154, -0.0726)); stations.add(new Station("4", "All Saints", 51.5107, -0.013)); stations.add(new Station("5", "Alperton", 51.5407, -0.2997)); stations.add(new Station("6", "Amersham", 51.6736, -0.607)); stations.add(new Station("7", "Angel", 51.5322, -0.1058)); stations.add(new Station("8", "Archway", 51.5653, -0.1353)); stations.add(new Station("9", "Arnos Grove", 51.6164, -0.1331)); stations.add(new Station("10", "Arsenal", 51.5586, -0.1059)); stations.add(new Station("11", "Baker Street", 51.5226, -0.1571)); stations.add(new Station("12", "Balham", 51.4431, -0.1525)); stations.add(new Station("13", "Bank", 51.5133, -0.0886)); stations.add(new Station("14", "Barbican", 51.5204, -0.0979)); stations.add(new Station("15", "Barking", 51.5396, 0.081)); stations.add(new Station("16", "Barkingside", 51.5856, 0.0887)); stations.add(new Station("17", "Barons Court", 51.4905, -0.2139)); stations.add(new Station("18", "Bayswater", 51.5121, -0.1879)); stations.add(new Station("19", "Beckton", 51.5148, 0.0613)); stations.add(new Station("20", "Beckton Park", 51.5087, 0.055)); stations.add(new Station("21", "Becontree", 51.5403, 0.127)); stations.add(new Station("22", "Belsize Park", 51.5504, -0.1642)); stations.add(new Station("23", "Bermondsey", 51.4979, -0.0637)); stations.add(new Station("24", "Bethnal Green", 51.527, -0.0549)); stations.add(new Station("25", "Blackfriars", 51.512, -0.1031)); stations.add(new Station("26", "Blackhorse Road", 51.5867, -0.0417)); stations.add(new Station("27", "Blackwall", 51.5079, -0.0066)); stations.add(new Station("28", "Bond Street", 51.5142, -0.1494)); stations.add(new Station("29", "Borough", 51.5011, -0.0943)); stations.add(new Station("30", "Boston Manor", 51.4956, -0.325)); stations.add(new Station("31", "Bounds Green", 51.6071, -0.1243)); stations.add(new Station("32", "Bow Church", 51.5273, -0.0208)); stations.add(new Station("33", "Bow Road", 51.5269, -0.0247)); stations.add(new Station("34", "Brent Cross", 51.5766, -0.2136)); stations.add(new Station("35", "Brixton", 51.4627, -0.1145)); stations.add(new Station("36", "Bromley-By-Bow", 51.5248, -0.0119)); stations.add(new Station("37", "Buckhurst Hill", 51.6266, 0.0471)); stations.add(new Station("38", "Burnt Oak", 51.6028, -0.2641)); stations.add(new Station("39", "Caledonian Road", 51.5481, -0.1188)); stations.add(new Station("40", "Camden Town", 51.5392, -0.1426)); stations.add(new Station("41", "Canada Water", 51.4982, -0.0502)); stations.add(new Station("42", "Canary Wharf", 51.5051, -0.0209)); stations.add(new Station("43", "Canning Town", 51.5147, 0.0082)); stations.add(new Station("44", "Cannon Street", 51.5113, -0.0904)); stations.add(new Station("45", "Canons Park", 51.6078, -0.2947)); stations.add(new Station("46", "Chalfont & Latimer", 51.6679, -0.561)); stations.add(new Station("47", "Chalk Farm", 51.5441, -0.1538)); stations.add(new Station("48", "Chancery Lane", 51.5185, -0.1111)); stations.add(new Station("49", "Charing Cross", 51.508, -0.1247)); stations.add(new Station("50", "Chesham", 51.7052, -0.611)); stations.add(new Station("51", "Chigwell", 51.6177, 0.0755)); stations.add(new Station("52", "Chiswick Park", 51.4946, -0.2678)); stations.add(new Station("53", "Chorleywood", 51.6543, -0.5183)); stations.add(new Station("54", "Clapham Common", 51.4618, -0.1384)); stations.add(new Station("55", "Clapham North", 51.4649, -0.1299)); stations.add(new Station("56", "Clapham South", 51.4527, -0.148)); stations.add(new Station("57", "Cockfosters", 51.6517, -0.1496)); stations.add(new Station("58", "Colindale", 51.5955, -0.2502)); stations.add(new Station("59", "Colliers Wood", 51.418, -0.1778)); stations.add(new Station("60", "Covent Garden", 51.5129, -0.1243)); stations.add(new Station("61", "Crossharbour & London Arena", 51.4957, -0.0144)); stations.add(new Station("62", "Croxley", 51.647, -0.4412)); stations.add(new Station("63", "Custom House", 51.5095, 0.0276)); stations.add(new Station("64", "Cutty Sark", 51.4827, -0.0096)); stations.add(new Station("65", "Cyprus", 51.5085, 0.064)); stations.add(new Station("66", "Dagenham East", 51.5443, 0.1655)); stations.add(new Station("67", "Dagenham Heathway", 51.5417, 0.1469)); stations.add(new Station("68", "Debden", 51.6455, 0.0838)); stations.add(new Station("69", "Deptford Bridge", 51.474, -0.0216)); stations.add(new Station("70", "Devons Road", 51.5223, -0.0173)); stations.add(new Station("71", "Dollis Hill", 51.552, -0.2387)); stations.add(new Station("72", "Ealing Broadway", 51.5152, -0.3017)); stations.add(new Station("73", "Ealing Common", 51.5101, -0.2882)); stations.add(new Station("74", "Earl's Court", 51.492, -0.1973)); stations.add(new Station("75", "Eastcote", 51.5765, -0.397)); stations.add(new Station("76", "East Acton", 51.5168, -0.2474)); stations.add(new Station("77", "East Finchley", 51.5874, -0.165)); stations.add(new Station("78", "East Ham", 51.5394, 0.0518)); stations.add(new Station("79", "East India", 51.5093, -0.0021)); stations.add(new Station("80", "East Putney", 51.4586, -0.2112)); stations.add(new Station("81", "Edgware", 51.6137, -0.275)); stations.add(new Station("82", "Edgware Road (B)", 51.5199, -0.1679)); stations.add(new Station("83", "Edgware Road (C)", 51.5203, -0.17)); stations.add(new Station("84", "Elephant & Castle", 51.4943, -0.1001)); stations.add(new Station("85", "Elm Park", 51.5496, 0.1977)); stations.add(new Station("86", "Elverson Road", 51.4693, -0.0174)); stations.add(new Station("87", "Embankment", 51.5074, -0.1223)); stations.add(new Station("88", "Epping", 51.6937, 0.1139)); stations.add(new Station("89", "Euston", 51.5282, -0.1337)); stations.add(new Station("90", "Euston Square", 51.526, -0.1359)); stations.add(new Station("91", "Fairlop", 51.596, 0.0912)); stations.add(new Station("92", "Farringdon", 51.5203, -0.1053)); stations.add(new Station("93", "Finchley Central", 51.6012, -0.1932)); stations.add(new Station("94", "Finchley Road", 51.5472, -0.1803)); stations.add(new Station("95", "Finsbury Park", 51.5642, -0.1065)); stations.add(new Station("96", "Fulham Broadway", 51.4804, -0.195)); stations.add(new Station("97", "Gallions Reach", 51.5096, 0.0716)); stations.add(new Station("98", "Gants Hill", 51.5765, 0.0663)); stations.add(new Station("99", "Gloucester Road", 51.4945, -0.1829)); stations.add(new Station("100", "Golders Green", 51.5724, -0.1941)); stations.add(new Station("101", "Goldhawk Road", 51.5018, -0.2267)); stations.add(new Station("102", "Goodge Street", 51.5205, -0.1347)); stations.add(new Station("103", "Grange Hill", 51.6132, 0.0923)); stations.add(new Station("104", "Great Portland Street", 51.5238, -0.1439)); stations.add(new Station("105", "Greenford", 51.5423, -0.3456)); stations.add(new Station("106", "Greenwich", 51.4781, -0.0149)); stations.add(new Station("107", "Green Park", 51.5067, -0.1428)); stations.add(new Station("108", "Gunnersbury", 51.4915, -0.2754)); stations.add(new Station("109", "Hainault", 51.603, 0.0933)); stations.add(new Station("110", "Hammersmith", 51.4936, -0.2251)); stations.add(new Station("111", "Hampstead", 51.5568, -0.178)); stations.add(new Station("112", "Hanger Lane", 51.5302, -0.2933)); stations.add(new Station("113", "Harlesden", 51.5362, -0.2575)); stations.add(new Station("114", "Harrow & Wealdston", 51.5925, -0.3351)); stations.add(new Station("115", "Harrow-on-the-Hill", 51.5793, -0.3366)); stations.add(new Station("116", "Hatton Cross", 51.4669, -0.4227)); stations.add(new Station("117", "Heathrow Terminals 1, 2 & 3", 51.4713, -0.4524)); stations.add(new Station("118", "Heathrow Terminal 4", 51.4598, -0.4476)); stations.add(new Station("119", "Hendon Central", 51.5829, -0.2259)); stations.add(new Station("120", "Heron Quays", 51.5033, -0.0215)); stations.add(new Station("121", "High Barnet", 51.6503, -0.1943)); stations.add(new Station("122", "High Street Kensington", 51.5009, -0.1925)); stations.add(new Station("123", "Highbury & Islington", 51.546, -0.104)); stations.add(new Station("124", "Highgate", 51.5777, -0.1458)); stations.add(new Station("125", "Hillingdon", 51.5538, -0.4499)); stations.add(new Station("126", "Holborn", 51.5174, -0.12)); stations.add(new Station("127", "Holland Park", 51.5075, -0.206)); stations.add(new Station("128", "Holloway Road", 51.5526, -0.1132)); stations.add(new Station("129", "Hornchurch", 51.5539, 0.2184)); stations.add(new Station("130", "Hounslow Central", 51.4713, -0.3665)); stations.add(new Station("131", "Hounslow East", 51.4733, -0.3564)); stations.add(new Station("132", "Hounslow West", 51.4734, -0.3855)); stations.add(new Station("133", "Hyde Park Corner", 51.5027, -0.1527)); stations.add(new Station("134", "Ickenham", 51.5619, -0.4421)); stations.add(new Station("135", "Island Gardens", 51.4871, -0.0101)); stations.add(new Station("136", "Kennington", 51.4884, -0.1053)); stations.add(new Station("137", "Kensal Green", 51.5304, -0.225)); stations.add(new Station("138", "Kensington (Olympia)", 51.4983, -0.2106)); stations.add(new Station("139", "Kentish Town", 51.5507, -0.1402)); stations.add(new Station("140", "Kenton", 51.5816, -0.3162)); stations.add(new Station("141", "Kew Gardens", 51.477, -0.285)); stations.add(new Station("142", "Kilburn", 51.5471, -0.2047)); stations.add(new Station("143", "Kilburn Park", 51.5351, -0.1939)); stations.add(new Station("144", "Kingsbury", 51.5846, -0.2786)); stations.add(new Station("145", "King's Cross St. Pancras", 51.5308, -0.1238)); stations.add(new Station("146", "Knightsbridge", 51.5015, -0.1607)); stations.add(new Station("147", "Ladbroke Grove", 51.5172, -0.2107)); stations.add(new Station("148", "Lambeth North", 51.4991, -0.1115)); stations.add(new Station("149", "Lancaster Gate", 51.5119, -0.1756)); stations.add(new Station("150", "Latimer Road", 51.5139, -0.2172)); stations.add(new Station("151", "Leicester Square", 51.5113, -0.1281)); stations.add(new Station("152", "Lewisham", 51.4657, -0.0142)); stations.add(new Station("153", "Leyton", 51.5566, -0.0053)); stations.add(new Station("154", "Leytonstone", 51.5683, 0.0083)); stations.add(new Station("155", "Limehouse", 51.5123, -0.0396)); stations.add(new Station("156", "Liverpool Street", 51.5178, -0.0823)); stations.add(new Station("157", "London Bridge", 51.5052, -0.0864)); stations.add(new Station("158", "Loughton", 51.6412, 0.0558)); stations.add(new Station("159", "Maida Vale", 51.53, -0.1854)); stations.add(new Station("160", "Manor House", 51.5712, -0.0958)); stations.add(new Station("161", "Mansion House", 51.5122, -0.094)); stations.add(new Station("162", "Marble Arch", 51.5136, -0.1586)); stations.add(new Station("163", "Marylebone", 51.5225, -0.1631)); stations.add(new Station("164", "Mile End", 51.5249, -0.0332)); stations.add(new Station("165", "Mill Hill East", 51.6082, -0.2103)); stations.add(new Station("166", "Monument", 51.5108, -0.0863)); stations.add(new Station("167", "Moorgate", 51.5186, -0.0886)); stations.add(new Station("168", "Moor Park", 51.6294, -0.432)); stations.add(new Station("169", "Morden", 51.4022, -0.1948)); stations.add(new Station("170", "Mornington Crescent", 51.5342, -0.1387)); stations.add(new Station("171", "Mudchute", 51.4902, -0.0145)); stations.add(new Station("172", "Neasden", 51.5542, -0.2503)); stations.add(new Station("173", "Newbury Park", 51.5756, 0.0899)); stations.add(new Station("174", "New Cross", 51.4767, -0.0327)); stations.add(new Station("175", "New Cross Gate", 51.4757, -0.0402)); stations.add(new Station("176", "Northfields", 51.4995, -0.3142)); stations.add(new Station("177", "Northolt", 51.5483, -0.3687)); stations.add(new Station("178", "Northwick Park", 51.5784, -0.3184)); stations.add(new Station("179", "Northwood", 51.6111, -0.424)); stations.add(new Station("180", "Northwood Hills", 51.6004, -0.4092)); stations.add(new Station("181", "North Acton", 51.5237, -0.2597)); stations.add(new Station("182", "North Ealing", 51.5175, -0.2887)); stations.add(new Station("183", "North Greenwich", 51.5005, 0.0039)); stations.add(new Station("184", "North Harrow", 51.5846, -0.3626)); stations.add(new Station("185", "North Wembley", 51.5621, -0.3034)); stations.add(new Station("186", "Notting Hill Gate", 51.5094, -0.1967)); stations.add(new Station("187", "Oakwood", 51.6476, -0.1318)); stations.add(new Station("188", "Old Street", 51.5263, -0.0873)); stations.add(new Station("189", "Osterley", 51.4813, -0.3522)); stations.add(new Station("190", "Oval", 51.4819, -0.113)); stations.add(new Station("191", "Oxford Circus", 51.515, -0.1415)); stations.add(new Station("192", "Paddington", 51.5154, -0.1755)); stations.add(new Station("193", "Park Royal", 51.527, -0.2841)); stations.add(new Station("194", "Parsons Green", 51.4753, -0.2011)); stations.add(new Station("195", "Perivale", 51.5366, -0.3232)); stations.add(new Station("196", "Picadilly Circus", 51.5098, -0.1342)); stations.add(new Station("197", "Pimlico", 51.4893, -0.1334)); stations.add(new Station("198", "Pinner", 51.5926, -0.3805)); stations.add(new Station("199", "Plaistow", 51.5313, 0.0172)); stations.add(new Station("200", "Poplar", 51.5077, -0.0173)); stations.add(new Station("201", "Preston Road", 51.572, -0.2954)); stations.add(new Station("202", "Prince Regent", 51.5093, 0.0336)); stations.add(new Station("203", "Pudding Mill Lane", 51.5343, -0.0139)); stations.add(new Station("204", "Putney Bridge", 51.4682, -0.2089)); stations.add(new Station("205", "Queen's Park", 51.5341, -0.2047)); stations.add(new Station("206", "Queensbury", 51.5942, -0.2861)); stations.add(new Station("207", "Queensway", 51.5107, -0.1877)); stations.add(new Station("208", "Ravenscourt Park", 51.4942, -0.2359)); stations.add(new Station("209", "Rayners Lane", 51.5753, -0.3714)); stations.add(new Station("210", "Redbridge", 51.5763, 0.0454)); stations.add(new Station("211", "Regent's Park", 51.5234, -0.1466)); stations.add(new Station("212", "Richmond", 51.4633, -0.3013)); stations.add(new Station("213", "Rickmansworth", 51.6404, -0.4733)); stations.add(new Station("214", "Roding Valley", 51.6171, 0.0439)); stations.add(new Station("215", "Rotherhithe", 51.501, -0.0525)); stations.add(new Station("216", "Royal Albert", 51.5084, 0.0465)); stations.add(new Station("217", "Royal Oak", 51.519, -0.188)); stations.add(new Station("218", "Royal Victoria", 51.5091, 0.0181)); stations.add(new Station("219", "Ruislip", 51.5715, -0.4213)); stations.add(new Station("220", "Ruislip Gardens", 51.5606, -0.4103)); stations.add(new Station("221", "Ruislip Manor", 51.5732, -0.4125)); stations.add(new Station("222", "Russell Square", 51.523, -0.1244)); stations.add(new Station("223", "Seven Sisters", 51.5822, -0.0749)); stations.add(new Station("224", "Shadwell", 51.5117, -0.056)); stations.add(new Station("225", "Shepherd's Bush (C)", 51.5046, -0.2187)); stations.add(new Station("226", "Shepherd's Bush (H)", 51.5058, -0.2265)); stations.add(new Station("227", "Shoreditch", 51.5227, -0.0708)); stations.add(new Station("228", "Sloane Square", 51.4924, -0.1565)); stations.add(new Station("229", "Snaresbrook", 51.5808, 0.0216)); stations.add(new Station("230", "Southfields", 51.4454, -0.2066)); stations.add(new Station("231", "Southgate", 51.6322, -0.128)); stations.add(new Station("232", "Southwark", 51.501, -0.1052)); stations.add(new Station("233", "South Ealing", 51.5011, -0.3072)); stations.add(new Station("234", "South Harrow", 51.5646, -0.3521)); stations.add(new Station("235", "South Kensington", 51.4941, -0.1738)); stations.add(new Station("236", "South Kenton", 51.5701, -0.3081)); stations.add(new Station("237", "South Quay", 51.5007, -0.0191)); stations.add(new Station("238", "South Ruislip", 51.5569, -0.3988)); stations.add(new Station("239", "South Wimbledon", 51.4154, -0.1919)); stations.add(new Station("240", "South Woodford", 51.5917, 0.0275)); stations.add(new Station("241", "Stamford Brook", 51.495, -0.2459)); stations.add(new Station("242", "Stanmore", 51.6194, -0.3028)); stations.add(new Station("243", "Stepney Green", 51.5221, -0.047)); stations.add(new Station("244", "Stockwell", 51.4723, -0.123)); stations.add(new Station("245", "Stonebridge Park", 51.5439, -0.2759)); stations.add(new Station("246", "Stratford", 51.5416, -0.0042)); stations.add(new Station("247", "St. James's Park", 51.4994, -0.1335)); stations.add(new Station("248", "St. John's Wood", 51.5347, -0.174)); stations.add(new Station("249", "St. Paul's", 51.5146, -0.0973)); stations.add(new Station("250", "Sudbury Hill", 51.5569, -0.3366)); stations.add(new Station("251", "Sudbury Town", 51.5507, -0.3156)); stations.add(new Station("252", "Surrey Quays", 51.4933, -0.0478)); stations.add(new Station("253", "Swiss Cottage", 51.5432, -0.1738)); stations.add(new Station("254", "Temple", 51.5111, -0.1141)); stations.add(new Station("255", "Theydon Bois", 51.6717, 0.1033)); stations.add(new Station("256", "Tooting Bec", 51.4361, -0.1598)); stations.add(new Station("257", "Tooting Broadway", 51.4275, -0.168)); stations.add(new Station("258", "Tottenham Court Road", 51.5165, -0.131)); stations.add(new Station("259", "Tottenham Hale", 51.5882, -0.0594)); stations.add(new Station("260", "Totteridge & Whetstone", 51.6302, -0.1791)); stations.add(new Station("261", "Tower Gateway", 51.5106, -0.0743)); stations.add(new Station("262", "Tower Hill", 51.5098, -0.0766)); stations.add(new Station("263", "Tufnell Park", 51.5567, -0.1374)); stations.add(new Station("264", "Turnham Green", 51.4951, -0.2547)); stations.add(new Station("265", "Turnpike Lane", 51.5904, -0.1028)); stations.add(new Station("266", "Upminster", 51.559, 0.251)); stations.add(new Station("267", "Upminster Bridge", 51.5582, 0.2343)); stations.add(new Station("268", "Upney", 51.5385, 0.1014)); stations.add(new Station("269", "Upton Park", 51.5352, 0.0343)); stations.add(new Station("270", "Uxbridge", 51.5463, -0.4786)); stations.add(new Station("271", "Vauxhall", 51.4861, -0.1253)); stations.add(new Station("272", "Victoria", 51.4965, -0.1447)); stations.add(new Station("273", "Walthamstow Central", 51.583, -0.0195)); stations.add(new Station("274", "Wanstead", 51.5775, 0.0288)); stations.add(new Station("275", "Wapping", 51.5043, -0.0558)); stations.add(new Station("276", "Warren Street", 51.5247, -0.1384)); stations.add(new Station("277", "Warwick Avenue", 51.5235, -0.1835)); stations.add(new Station("278", "Waterloo", 51.5036, -0.1143)); stations.add(new Station("279", "Watford", 51.6573, -0.4177)); stations.add(new Station("280", "Wembley Central", 51.5519, -0.2963)); stations.add(new Station("281", "Wembley Park", 51.5635, -0.2795)); stations.add(new Station("282", "Westbourne Park", 51.521, -0.2011)); stations.add(new Station("283", "Westferry", 51.5097, -0.0265)); stations.add(new Station("284", "Westminster", 51.501, -0.1254)); stations.add(new Station("285", "West Acton", 51.518, -0.2809)); stations.add(new Station("286", "West Brompton", 51.4872, -0.1953)); stations.add(new Station("287", "West Finchley", 51.6095, -0.1883)); stations.add(new Station("288", "West Ham", 51.5287, 0.0056)); stations.add(new Station("289", "West Hampstead", 51.5469, -0.1906)); stations.add(new Station("290", "West Harrow", 51.5795, -0.3533)); stations.add(new Station("291", "West India Quay", 51.507, -0.0203)); stations.add(new Station("292", "West Kensington", 51.4907, -0.2065)); stations.add(new Station("293", "West Ruislip", 51.5696, -0.4376)); stations.add(new Station("294", "Whitechapel", 51.5194, -0.0612)); stations.add(new Station("295", "White City", 51.512, -0.2239)); stations.add(new Station("296", "Willesden Green", 51.5492, -0.2215)); stations.add(new Station("297", "Willesden Junction", 51.5326, -0.2478)); stations.add(new Station("298", "Wimbledon", 51.4214, -0.2064)); stations.add(new Station("299", "Wimbledon Park", 51.4343, -0.1992)); stations.add(new Station("300", "Woodford", 51.607, 0.0341)); stations.add(new Station("301", "Woodside Park", 51.6179, -0.1856)); stations.add(new Station("302", "Wood Green", 51.5975, -0.1097)); connections.put("1", Stream.of("52","73","73","233","264").collect(Collectors.toSet())); connections.put("2", Stream.of("156","262","156").collect(Collectors.toSet())); connections.put("3", Stream.of("262","294","156","294").collect(Collectors.toSet())); connections.put("4", Stream.of("70","200").collect(Collectors.toSet())); connections.put("5", Stream.of("193","251").collect(Collectors.toSet())); connections.put("6", Stream.of("46").collect(Collectors.toSet())); connections.put("7", Stream.of("145","188").collect(Collectors.toSet())); connections.put("8", Stream.of("124","263").collect(Collectors.toSet())); connections.put("9", Stream.of("31","231").collect(Collectors.toSet())); connections.put("10", Stream.of("95","128").collect(Collectors.toSet())); connections.put("11", Stream.of("163","211","83","104","83","104","28","248","94","104").collect(Collectors.toSet())); connections.put("12", Stream.of("56","256").collect(Collectors.toSet())); connections.put("13", Stream.of("156","249","224","157","167","278").collect(Collectors.toSet())); connections.put("14", Stream.of("92","167","92","167","92","167").collect(Collectors.toSet())); connections.put("15", Stream.of("78","268","78").collect(Collectors.toSet())); connections.put("16", Stream.of("91","173").collect(Collectors.toSet())); connections.put("17", Stream.of("110","292","74","110").collect(Collectors.toSet())); connections.put("18", Stream.of("186","192","186","192").collect(Collectors.toSet())); connections.put("19", Stream.of("97").collect(Collectors.toSet())); connections.put("20", Stream.of("65","216").collect(Collectors.toSet())); connections.put("21", Stream.of("67","268").collect(Collectors.toSet())); connections.put("22", Stream.of("47","111").collect(Collectors.toSet())); connections.put("23", Stream.of("41","157").collect(Collectors.toSet())); connections.put("24", Stream.of("156","164").collect(Collectors.toSet())); connections.put("25", Stream.of("161","254","161","254").collect(Collectors.toSet())); connections.put("26", Stream.of("259","273").collect(Collectors.toSet())); connections.put("27", Stream.of("79","200").collect(Collectors.toSet())); connections.put("28", Stream.of("162","191","11","107").collect(Collectors.toSet())); connections.put("29", Stream.of("84","157").collect(Collectors.toSet())); connections.put("30", Stream.of("176","189").collect(Collectors.toSet())); connections.put("31", Stream.of("9","302").collect(Collectors.toSet())); connections.put("32", Stream.of("70","203").collect(Collectors.toSet())); connections.put("33", Stream.of("36","164","36","164").collect(Collectors.toSet())); connections.put("34", Stream.of("100","119").collect(Collectors.toSet())); connections.put("35", Stream.of("244").collect(Collectors.toSet())); connections.put("36", Stream.of("33","288","33","288").collect(Collectors.toSet())); connections.put("37", Stream.of("158","300").collect(Collectors.toSet())); connections.put("38", Stream.of("58","81").collect(Collectors.toSet())); connections.put("39", Stream.of("128","145").collect(Collectors.toSet())); connections.put("40", Stream.of("47","89","139","170").collect(Collectors.toSet())); connections.put("41", Stream.of("215","252","23","42").collect(Collectors.toSet())); connections.put("42", Stream.of("120","291","41","183").collect(Collectors.toSet())); connections.put("43", Stream.of("79","218","183","288").collect(Collectors.toSet())); connections.put("44", Stream.of("161","166","161","166").collect(Collectors.toSet())); connections.put("45", Stream.of("206","242").collect(Collectors.toSet())); connections.put("46", Stream.of("6","50","53").collect(Collectors.toSet())); connections.put("47", Stream.of("22","40").collect(Collectors.toSet())); connections.put("48", Stream.of("126","249").collect(Collectors.toSet())); connections.put("49", Stream.of("87","196","87","151").collect(Collectors.toSet())); connections.put("50", Stream.of("46").collect(Collectors.toSet())); connections.put("51", Stream.of("103","214").collect(Collectors.toSet())); connections.put("52", Stream.of("1","264").collect(Collectors.toSet())); connections.put("53", Stream.of("46","213").collect(Collectors.toSet())); connections.put("54", Stream.of("55","56").collect(Collectors.toSet())); connections.put("55", Stream.of("54","244").collect(Collectors.toSet())); connections.put("56", Stream.of("12","54").collect(Collectors.toSet())); connections.put("57", Stream.of("187").collect(Collectors.toSet())); connections.put("58", Stream.of("38","119").collect(Collectors.toSet())); connections.put("59", Stream.of("239","257").collect(Collectors.toSet())); connections.put("60", Stream.of("126","151").collect(Collectors.toSet())); connections.put("61", Stream.of("171","237").collect(Collectors.toSet())); connections.put("62", Stream.of("168","279").collect(Collectors.toSet())); connections.put("63", Stream.of("202","218").collect(Collectors.toSet())); connections.put("64", Stream.of("106","135").collect(Collectors.toSet())); connections.put("65", Stream.of("20","97").collect(Collectors.toSet())); connections.put("66", Stream.of("67","85").collect(Collectors.toSet())); connections.put("67", Stream.of("21","66").collect(Collectors.toSet())); connections.put("68", Stream.of("158","255").collect(Collectors.toSet())); connections.put("69", Stream.of("86","106").collect(Collectors.toSet())); connections.put("70", Stream.of("4","32").collect(Collectors.toSet())); connections.put("71", Stream.of("172","296").collect(Collectors.toSet())); connections.put("72", Stream.of("285","73").collect(Collectors.toSet())); connections.put("73", Stream.of("72","1","1","182").collect(Collectors.toSet())); connections.put("74", Stream.of("99","122","138","286","292","17","99").collect(Collectors.toSet())); connections.put("75", Stream.of("209","221","209","221").collect(Collectors.toSet())); connections.put("76", Stream.of("181","295").collect(Collectors.toSet())); connections.put("77", Stream.of("93","124").collect(Collectors.toSet())); connections.put("78", Stream.of("15","269","15","269").collect(Collectors.toSet())); connections.put("79", Stream.of("27","43").collect(Collectors.toSet())); connections.put("80", Stream.of("204","230").collect(Collectors.toSet())); connections.put("81", Stream.of("38").collect(Collectors.toSet())); connections.put("82", Stream.of("163","192").collect(Collectors.toSet())); connections.put("83", Stream.of("11","192","192","11","192").collect(Collectors.toSet())); connections.put("84", Stream.of("148","29","136").collect(Collectors.toSet())); connections.put("85", Stream.of("66","129").collect(Collectors.toSet())); connections.put("86", Stream.of("69","152").collect(Collectors.toSet())); connections.put("87", Stream.of("49","278","254","284","254","284","49","278").collect(Collectors.toSet())); connections.put("88", Stream.of("255").collect(Collectors.toSet())); connections.put("89", Stream.of("40","145","170","276","145","276").collect(Collectors.toSet())); connections.put("90", Stream.of("104","145","104","145","104","145").collect(Collectors.toSet())); connections.put("91", Stream.of("16","109").collect(Collectors.toSet())); connections.put("92", Stream.of("14","145","14","145","14","145").collect(Collectors.toSet())); connections.put("93", Stream.of("77","165","287").collect(Collectors.toSet())); connections.put("94", Stream.of("253","289","11","281").collect(Collectors.toSet())); connections.put("95", Stream.of("10","160","123","223").collect(Collectors.toSet())); connections.put("96", Stream.of("194","286").collect(Collectors.toSet())); connections.put("97", Stream.of("19","65").collect(Collectors.toSet())); connections.put("98", Stream.of("173","210").collect(Collectors.toSet())); connections.put("99", Stream.of("122","235","74","235","74","235").collect(Collectors.toSet())); connections.put("100", Stream.of("34","111").collect(Collectors.toSet())); connections.put("101", Stream.of("110","226").collect(Collectors.toSet())); connections.put("102", Stream.of("258","276").collect(Collectors.toSet())); connections.put("103", Stream.of("51","109").collect(Collectors.toSet())); connections.put("104", Stream.of("11","90","11","90","11","90").collect(Collectors.toSet())); connections.put("105", Stream.of("177","195").collect(Collectors.toSet())); connections.put("106", Stream.of("64","69").collect(Collectors.toSet())); connections.put("107", Stream.of("28","284","133","196","191","272").collect(Collectors.toSet()));
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
true
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java
package com.baeldung.jgrapht; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.IntStream; import org.jgrapht.DirectedGraph; import org.jgrapht.GraphPath; import org.jgrapht.alg.CycleDetector; import org.jgrapht.alg.KosarajuStrongConnectivityInspector; import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm; import org.jgrapht.alg.shortestpath.AllDirectedPaths; import org.jgrapht.alg.shortestpath.BellmanFordShortestPath; import org.jgrapht.alg.shortestpath.DijkstraShortestPath; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedSubgraph; import org.jgrapht.traverse.BreadthFirstIterator; import org.jgrapht.traverse.DepthFirstIterator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class DirectedGraphUnitTest { DirectedGraph<String, DefaultEdge> directedGraph; @BeforeEach public void createDirectedGraph() { directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); IntStream.range(1, 10).forEach(i -> { directedGraph.addVertex("v" + i); }); directedGraph.addEdge("v1", "v2"); directedGraph.addEdge("v2", "v4"); directedGraph.addEdge("v4", "v3"); directedGraph.addEdge("v3", "v1"); directedGraph.addEdge("v5", "v4"); directedGraph.addEdge("v5", "v6"); directedGraph.addEdge("v6", "v7"); directedGraph.addEdge("v7", "v5"); directedGraph.addEdge("v8", "v5"); directedGraph.addEdge("v9", "v8"); } @Test void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); String randomVertex1 = stronglyConnectedVertices.get(0); String randomVertex2 = stronglyConnectedVertices.get(3); AllDirectedPaths<String, DefaultEdge> allDirectedPaths = new AllDirectedPaths<>(directedGraph); List<GraphPath<String, DefaultEdge>> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size()); assertTrue(possiblePathList.size() > 0); } @Test void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph); assertTrue(cycleDetector.detectCycles()); Set<String> cycleVertices = cycleDetector.findCycles(); assertTrue(cycleVertices.size() > 0); } @Test void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); assertNotNull(depthFirstIterator); } @Test void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); assertNotNull(breadthFirstIterator); } @Test void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); assertNotNull(shortestPath); } @Test void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); assertNotNull(shortestPath); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java
package com.baeldung.jgrapht; import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.jgrapht.ext.JGraphXAdapter; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.mxgraph.layout.mxCircleLayout; import com.mxgraph.layout.mxIGraphLayout; import com.mxgraph.util.mxCellRenderer; class GraphImageGenerationUnitTest { static DefaultDirectedGraph<String, DefaultEdge> g; @BeforeEach public void createGraph() throws IOException { File imgFile = new File("src/test/resources/graph1.png"); imgFile.createNewFile(); g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); String x1 = "x1"; String x2 = "x2"; String x3 = "x3"; g.addVertex(x1); g.addVertex(x2); g.addVertex(x3); g.addEdge(x1, x2); g.addEdge(x2, x3); g.addEdge(x3, x1); } @AfterEach public void cleanup() { File imgFile = new File("src/test/resources/graph1.png"); imgFile.deleteOnExit(); } @Test void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g); mxIGraphLayout layout = new mxCircleLayout(graphAdapter); layout.execute(graphAdapter.getDefaultParent()); File imgFile = new File("src/test/resources/graph1.png"); BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null); ImageIO.write(image, "PNG", imgFile); assertTrue(imgFile.exists()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java
package com.baeldung.jgrapht; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.stream.IntStream; import org.jgrapht.GraphPath; import org.jgrapht.alg.cycle.HierholzerEulerianCycle; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleWeightedGraph; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class EulerianCircuitUnitTest { SimpleWeightedGraph<String, DefaultEdge> simpleGraph; @BeforeEach public void createGraphWithEulerianCircuit() { simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); IntStream.range(1, 6).forEach(i -> { simpleGraph.addVertex("v" + i); }); IntStream.range(1, 6).forEach(i -> { int endVertexNo = (i + 1) > 5 ? 1 : i + 1; simpleGraph.addEdge("v" + i, "v" + endVertexNo); }); } @Test public void givenGraph_whenCheckEluerianCycle_thenGetResult() { HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); assertTrue(eulerianCycle.isEulerian(simpleGraph)); } @Test public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() { HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph); assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java
algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java
package com.baeldung.jgrapht; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.jgrapht.VertexFactory; import org.jgrapht.alg.HamiltonianCycle; import org.jgrapht.generate.CompleteGraphGenerator; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleWeightedGraph; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class CompleteGraphUnitTest { static SimpleWeightedGraph<String, DefaultEdge> completeGraph; static int size = 10; @BeforeEach public void createCompleteGraph() { completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size); VertexFactory<String> vFactory = new VertexFactory<String>() { private int id = 0; public String createVertex() { return "v" + id++; } }; completeGenerator.generateGraph(completeGraph, vFactory, null); } @Test public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() { List<String> verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph); assertEquals(verticeList.size(), completeGraph.vertexSet().size()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
package com.baeldung.algorithms; import java.util.Scanner; import com.baeldung.algorithms.slope_one.SlopeOne; public class RunAlgorithm { public static void main(String[] args) throws InstantiationException, IllegalAccessException { Scanner in = new Scanner(System.in); System.out.println("1 - Slope One"); System.out.println("2 - Dijkstra"); int decision = in.nextInt(); switch (decision) { case 1: SlopeOne.slopeOne(3); break; case 2: System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest."); break; default: System.out.println("Unknown option"); break; } in.close(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java
package com.baeldung.algorithms.maze.solver; import java.io.File; import java.util.List; public class MazeDriver { public static void main(String[] args) throws Exception { File maze1 = new File("src/main/resources/maze/maze1.txt"); File maze2 = new File("src/main/resources/maze/maze2.txt"); execute(maze1); execute(maze2); } private static void execute(File file) throws Exception { Maze maze = new Maze(file); dfs(maze); bfs(maze); } private static void bfs(Maze maze) { BFSMazeSolver bfs = new BFSMazeSolver(); List<Coordinate> path = bfs.solve(maze); maze.printPath(path); maze.reset(); } private static void dfs(Maze maze) { DFSMazeSolver dfs = new DFSMazeSolver(); List<Coordinate> path = dfs.solve(maze); maze.printPath(path); maze.reset(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java
package com.baeldung.algorithms.maze.solver; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class BFSMazeSolver { private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; public List<Coordinate> solve(Maze maze) { LinkedList<Coordinate> nextToVisit = new LinkedList<>(); Coordinate start = maze.getEntry(); nextToVisit.add(start); while (!nextToVisit.isEmpty()) { Coordinate cur = nextToVisit.remove(); if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) { continue; } if (maze.isWall(cur.getX(), cur.getY())) { maze.setVisited(cur.getX(), cur.getY(), true); continue; } if (maze.isExit(cur.getX(), cur.getY())) { return backtrackPath(cur); } for (int[] direction : DIRECTIONS) { Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur); nextToVisit.add(coordinate); maze.setVisited(cur.getX(), cur.getY(), true); } } return Collections.emptyList(); } private List<Coordinate> backtrackPath(Coordinate cur) { List<Coordinate> path = new ArrayList<>(); Coordinate iter = cur; while (iter != null) { path.add(iter); iter = iter.parent; } return path; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java
package com.baeldung.algorithms.maze.solver; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class DFSMazeSolver { private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; public List<Coordinate> solve(Maze maze) { List<Coordinate> path = new ArrayList<>(); if (explore(maze, maze.getEntry() .getX(), maze.getEntry() .getY(), path)) { return path; } return Collections.emptyList(); } private boolean explore(Maze maze, int row, int col, List<Coordinate> path) { if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) { return false; } path.add(new Coordinate(row, col)); maze.setVisited(row, col, true); if (maze.isExit(row, col)) { return true; } for (int[] direction : DIRECTIONS) { Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]); if (explore(maze, coordinate.getX(), coordinate.getY(), path)) { return true; } } path.remove(path.size() - 1); return false; } private Coordinate getNextCoordinate(int row, int col, int i, int j) { return new Coordinate(row + i, col + j); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java
package com.baeldung.algorithms.maze.solver; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Maze { private static final int ROAD = 0; private static final int WALL = 1; private static final int START = 2; private static final int EXIT = 3; private static final int PATH = 4; private int[][] maze; private boolean[][] visited; private Coordinate start; private Coordinate end; public Maze(File maze) throws FileNotFoundException { String fileText = ""; try (Scanner input = new Scanner(maze)) { while (input.hasNextLine()) { fileText += input.nextLine() + "\n"; } } initializeMaze(fileText); } private void initializeMaze(String text) { if (text == null || (text = text.trim()).length() == 0) { throw new IllegalArgumentException("empty lines data"); } String[] lines = text.split("[\r]?\n"); maze = new int[lines.length][lines[0].length()]; visited = new boolean[lines.length][lines[0].length()]; for (int row = 0; row < getHeight(); row++) { if (lines[row].length() != getWidth()) { throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")"); } for (int col = 0; col < getWidth(); col++) { if (lines[row].charAt(col) == '#') maze[row][col] = WALL; else if (lines[row].charAt(col) == 'S') { maze[row][col] = START; start = new Coordinate(row, col); } else if (lines[row].charAt(col) == 'E') { maze[row][col] = EXIT; end = new Coordinate(row, col); } else maze[row][col] = ROAD; } } } public int getHeight() { return maze.length; } public int getWidth() { return maze[0].length; } public Coordinate getEntry() { return start; } public Coordinate getExit() { return end; } public boolean isExit(int x, int y) { return x == end.getX() && y == end.getY(); } public boolean isStart(int x, int y) { return x == start.getX() && y == start.getY(); } public boolean isExplored(int row, int col) { return visited[row][col]; } public boolean isWall(int row, int col) { return maze[row][col] == WALL; } public void setVisited(int row, int col, boolean value) { visited[row][col] = value; } public boolean isValidLocation(int row, int col) { if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) { return false; } return true; } public void printPath(List<Coordinate> path) { int[][] tempMaze = Arrays.stream(maze) .map(int[]::clone) .toArray(int[][]::new); for (Coordinate coordinate : path) { if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) { continue; } tempMaze[coordinate.getX()][coordinate.getY()] = PATH; } System.out.println(toString(tempMaze)); } public String toString(int[][] maze) { StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1)); for (int row = 0; row < getHeight(); row++) { for (int col = 0; col < getWidth(); col++) { if (maze[row][col] == ROAD) { result.append(' '); } else if (maze[row][col] == WALL) { result.append('#'); } else if (maze[row][col] == START) { result.append('S'); } else if (maze[row][col] == EXIT) { result.append('E'); } else { result.append('.'); } } result.append('\n'); } return result.toString(); } public void reset() { for (int i = 0; i < visited.length; i++) Arrays.fill(visited[i], false); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java
package com.baeldung.algorithms.maze.solver; public class Coordinate { int x; int y; Coordinate parent; public Coordinate(int x, int y) { this.x = x; this.y = y; this.parent = null; } public Coordinate(int x, int y, Coordinate parent) { this.x = x; this.y = y; this.parent = parent; } int getX() { return x; } int getY() { return y; } Coordinate getParent() { return parent; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java
package com.baeldung.algorithms.linkedlist; import java.util.HashSet; import java.util.Set; public class CycleDetectionByHashing { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Set<Node<T>> set = new HashSet<>(); Node<T> node = head; while (node != null) { if (set.contains(node)) { return new CycleDetectionResult<>(true, node); } set.add(node); node = node.next; } return new CycleDetectionResult<>(false, null); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/Node.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/Node.java
package com.baeldung.algorithms.linkedlist; public class Node<T> { T data; Node<T> next; public static <T> Node<T> createNewNode(T data, Node<T> next) { Node<T> node = new Node<T>(); node.data = data; node.next = next; return node; } public static <T> void traverseList(Node<T> root) { if (root == null) { return; } Node<T> node = root; while (node != null) { System.out.println(node.data); node = node.next; } } public static <T> Node<T> getTail(Node<T> root) { if (root == null) { return null; } Node<T> node = root; while (node.next != null) { node = node.next; } return node; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java
package com.baeldung.algorithms.linkedlist; public class CycleDetectionBruteForce { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Node<T> it1 = head; int nodesTraversedByOuter = 0; while (it1 != null && it1.next != null) { it1 = it1.next; nodesTraversedByOuter++; int x = nodesTraversedByOuter; Node<T> it2 = head; int noOfTimesCurrentNodeVisited = 0; while (x > 0) { it2 = it2.next; if (it2 == it1) { noOfTimesCurrentNodeVisited++; } if (noOfTimesCurrentNodeVisited == 2) { return new CycleDetectionResult<>(true, it1); } x--; } } return new CycleDetectionResult<>(false, null); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java
package com.baeldung.algorithms.linkedlist; public class CycleDetectionByFastAndSlowIterators { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Node<T> slow = head; Node<T> fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { return new CycleDetectionResult<>(true, fast); } } return new CycleDetectionResult<>(false, null); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java
package com.baeldung.algorithms.linkedlist; public class CycleRemovalBruteForce { public static <T> boolean detectAndRemoveCycle(Node<T> head) { CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); if (result.cycleExists) { removeCycle(result.node, head); } return result.cycleExists; } /** * @param loopNodeParam - reference to the node where Flyods cycle * finding algorithm ends, i.e. the fast and the slow iterators * meet. * @param head - reference to the head of the list */ private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) { Node<T> it = head; while (it != null) { if (isNodeReachableFromLoopNode(it, loopNodeParam)) { Node<T> loopStart = it; findEndNodeAndBreakCycle(loopStart); break; } it = it.next; } } private static <T> boolean isNodeReachableFromLoopNode(Node<T> it, Node<T> loopNodeParam) { Node<T> loopNode = loopNodeParam; do { if (it == loopNode) { return true; } loopNode = loopNode.next; } while (loopNode.next != loopNodeParam); return false; } private static <T> void findEndNodeAndBreakCycle(Node<T> loopStartParam) { Node<T> loopStart = loopStartParam; while (loopStart.next != loopStartParam) { loopStart = loopStart.next; } loopStart.next = null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java
package com.baeldung.algorithms.linkedlist; public class CycleRemovalWithoutCountingLoopNodes { public static <T> boolean detectAndRemoveCycle(Node<T> head) { CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); if (result.cycleExists) { removeCycle(result.node, head); } return result.cycleExists; } private static <T> void removeCycle(Node<T> meetingPointParam, Node<T> head) { Node<T> loopNode = meetingPointParam; Node<T> it = head; while (loopNode.next != it.next) { it = it.next; loopNode = loopNode.next; } loopNode.next = null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java
package com.baeldung.algorithms.linkedlist; public class CycleDetectionResult<T> { boolean cycleExists; Node<T> node; public CycleDetectionResult(boolean cycleExists, Node<T> node) { super(); this.cycleExists = cycleExists; this.node = node; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java
package com.baeldung.algorithms.linkedlist; public class CycleRemovalByCountingLoopNodes { public static <T> boolean detectAndRemoveCycle(Node<T> head) { CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); if (result.cycleExists) { removeCycle(result.node, head); } return result.cycleExists; } private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) { int cycleLength = calculateCycleLength(loopNodeParam); Node<T> cycleLengthAdvancedIterator = head; Node<T> it = head; for (int i = 0; i < cycleLength; i++) { cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; } while (it.next != cycleLengthAdvancedIterator.next) { it = it.next; cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; } cycleLengthAdvancedIterator.next = null; } private static <T> int calculateCycleLength(Node<T> loopNodeParam) { Node<T> loopNode = loopNodeParam; int length = 1; while (loopNode.next != loopNodeParam) { length++; loopNode = loopNode.next; } return length; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java
package com.baeldung.algorithms.numberwordconverter; import java.math.BigDecimal; import pl.allegro.finance.tradukisto.MoneyConverters; public class NumberWordConverter { public static final String INVALID_INPUT_GIVEN = "Invalid input given"; public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; public static final String[] tens = { "", // 0 "", // 1 "twenty", // 2 "thirty", // 3 "forty", // 4 "fifty", // 5 "sixty", // 6 "seventy", // 7 "eighty", // 8 "ninety" // 9 }; public static String getMoneyIntoWords(String input) { MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE; return converter.asWords(new BigDecimal(input)); } public static String getMoneyIntoWords(final double money) { long dollar = (long) money; long cents = Math.round((money - dollar) * 100); if (money == 0D) { return ""; } if (money < 0) { return INVALID_INPUT_GIVEN; } String dollarPart = ""; if (dollar > 0) { dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s"); } String centsPart = ""; if (cents > 0) { if (dollarPart.length() > 0) { centsPart = " and "; } centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s"); } return dollarPart + centsPart; } private static String convert(final long n) { if (n < 0) { return INVALID_INPUT_GIVEN; } if (n < 20) { return ones[(int) n]; } if (n < 100) { return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10]; } if (n < 1000) { return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100); } if (n < 1_000_000) { return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000); } if (n < 1_000_000_000) { return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000); } return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/BacktrackingAlgorithm.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/BacktrackingAlgorithm.java
package com.baeldung.algorithms.sudoku; import java.util.stream.IntStream; public class BacktrackingAlgorithm { private static final int BOARD_SIZE = 9; private static final int SUBSECTION_SIZE = 3; private static final int BOARD_START_INDEX = 0; private static final int NO_VALUE = 0; private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 9; private static final int[][] board = { {8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 3, 6, 0, 0, 0, 0, 0}, {0, 7, 0, 0, 9, 0, 2, 0, 0}, {0, 5, 0, 0, 0, 7, 0, 0, 0}, {0, 0, 0, 0, 4, 5, 7, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 3, 0}, {0, 0, 1, 0, 0, 0, 0, 6, 8}, {0, 0, 8, 5, 0, 0, 0, 1, 0}, {0, 9, 0, 0, 0, 0, 4, 0, 0} }; public static void main(String[] args) { BacktrackingAlgorithm solver = new BacktrackingAlgorithm(); solver.solve(board); solver.printBoard(); } private void printBoard() { for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) { for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) { System.out.print(board[row][column] + " "); } System.out.println(); } } public boolean solve(int[][] board) { for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) { for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) { if (board[row][column] == NO_VALUE) { for (int k = MIN_VALUE; k <= MAX_VALUE; k++) { board[row][column] = k; if (isValid(board, row, column) && solve(board)) { return true; } board[row][column] = NO_VALUE; } return false; } } } return true; } private boolean isValid(int[][] board, int row, int column) { return rowConstraint(board, row) && columnConstraint(board, column) && subsectionConstraint(board, row, column); } private boolean subsectionConstraint(int[][] board, int row, int column) { boolean[] constraint = new boolean[BOARD_SIZE]; int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE; int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE; int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE; int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE; for (int r = subsectionRowStart; r < subsectionRowEnd; r++) { for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) { if (!checkConstraint(board, r, constraint, c)) return false; } } return true; } private boolean columnConstraint(int[][] board, int column) { boolean[] constraint = new boolean[BOARD_SIZE]; for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) { if (!checkConstraint(board, row, constraint, column)) { return false; } } return true; } private boolean rowConstraint(int[][] board, int row) { boolean[] constraint = new boolean[BOARD_SIZE]; for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) { if (!checkConstraint(board, row, constraint, column)) { return false; } } return true; } private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) { if (board[row][column] != NO_VALUE) { if (!constraint[board[row][column] - 1]) { constraint[board[row][column] - 1] = true; } else { return false; } } return true; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/ColumnNode.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/ColumnNode.java
package com.baeldung.algorithms.sudoku; class ColumnNode extends DancingNode { int size; String name; ColumnNode(String n) { super(); size = 0; name = n; C = this; } void cover() { unlinkLR(); for (DancingNode i = this.D; i != this; i = i.D) { for (DancingNode j = i.R; j != i; j = j.R) { j.unlinkUD(); j.C.size--; } } } void uncover() { for (DancingNode i = this.U; i != this; i = i.U) { for (DancingNode j = i.L; j != i; j = j.L) { j.C.size++; j.relinkUD(); } } relinkLR(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinksAlgorithm.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinksAlgorithm.java
package com.baeldung.algorithms.sudoku; import java.util.Arrays; public class DancingLinksAlgorithm { private static final int BOARD_SIZE = 9; private static final int SUBSECTION_SIZE = 3; private static final int NO_VALUE = 0; private static final int CONSTRAINTS = 4; private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 9; private static final int COVER_START_INDEX = 1; private static final int[][] board = { {8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 3, 6, 0, 0, 0, 0, 0}, {0, 7, 0, 0, 9, 0, 2, 0, 0}, {0, 5, 0, 0, 0, 7, 0, 0, 0}, {0, 0, 0, 0, 4, 5, 7, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 3, 0}, {0, 0, 1, 0, 0, 0, 0, 6, 8}, {0, 0, 8, 5, 0, 0, 0, 1, 0}, {0, 9, 0, 0, 0, 0, 4, 0, 0} }; public static void main(String[] args) { DancingLinksAlgorithm solver = new DancingLinksAlgorithm(); solver.solve(board); } private void solve(int[][] board) { boolean[][] cover = initializeExactCoverBoard(board); DancingLinks dlx = new DancingLinks(cover); dlx.runSolver(); } private int getIndex(int row, int column, int num) { return (row - 1) * BOARD_SIZE * BOARD_SIZE + (column - 1) * BOARD_SIZE + (num - 1); } private boolean[][] createExactCoverBoard() { boolean[][] coverBoard = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS]; int hBase = 0; hBase = checkCellConstraint(coverBoard, hBase); hBase = checkRowConstraint(coverBoard, hBase); hBase = checkColumnConstraint(coverBoard, hBase); checkSubsectionConstraint(coverBoard, hBase); return coverBoard; } private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row += SUBSECTION_SIZE) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column += SUBSECTION_SIZE) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) { for (int rowDelta = 0; rowDelta < SUBSECTION_SIZE; rowDelta++) { for (int columnDelta = 0; columnDelta < SUBSECTION_SIZE; columnDelta++) { int index = getIndex(row + rowDelta, column + columnDelta, n); coverBoard[index][hBase] = true; } } } } } return hBase; } private int checkColumnConstraint(boolean[][] coverBoard, int hBase) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { int index = getIndex(row, column, n); coverBoard[index][hBase] = true; } } } return hBase; } private int checkRowConstraint(boolean[][] coverBoard, int hBase) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) { int index = getIndex(row, column, n); coverBoard[index][hBase] = true; } } } return hBase; } private int checkCellConstraint(boolean[][] coverBoard, int hBase) { for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) { for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) { int index = getIndex(row, column, n); coverBoard[index][hBase] = true; } } } return hBase; } private boolean[][] initializeExactCoverBoard(int[][] board) { boolean[][] coverBoard = createExactCoverBoard(); for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) { for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) { int n = board[row - 1][column - 1]; if (n != NO_VALUE) { for (int num = MIN_VALUE; num <= MAX_VALUE; num++) { if (num != n) { Arrays.fill(coverBoard[getIndex(row, column, num)], false); } } } } } return coverBoard; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingNode.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingNode.java
package com.baeldung.algorithms.sudoku; class DancingNode { DancingNode L, R, U, D; ColumnNode C; DancingNode hookDown(DancingNode node) { assert (this.C == node.C); node.D = this.D; node.D.U = node; node.U = this; this.D = node; return node; } DancingNode hookRight(DancingNode node) { node.R = this.R; node.R.L = node; node.L = this; this.R = node; return node; } void unlinkLR() { this.L.R = this.R; this.R.L = this.L; } void relinkLR() { this.L.R = this.R.L = this; } void unlinkUD() { this.U.D = this.D; this.D.U = this.U; } void relinkUD() { this.U.D = this.D.U = this; } DancingNode() { L = R = U = D = this; } DancingNode(ColumnNode c) { this(); C = c; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinks.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinks.java
package com.baeldung.algorithms.sudoku; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class DancingLinks { private ColumnNode header; private List<DancingNode> answer; private void search(int k) { if (header.R == header) { handleSolution(answer); } else { ColumnNode c = selectColumnNodeHeuristic(); c.cover(); for (DancingNode r = c.D; r != c; r = r.D) { answer.add(r); for (DancingNode j = r.R; j != r; j = j.R) { j.C.cover(); } search(k + 1); r = answer.remove(answer.size() - 1); c = r.C; for (DancingNode j = r.L; j != r; j = j.L) { j.C.uncover(); } } c.uncover(); } } private ColumnNode selectColumnNodeHeuristic() { int min = Integer.MAX_VALUE; ColumnNode ret = null; for (ColumnNode c = (ColumnNode) header.R; c != header; c = (ColumnNode) c.R) { if (c.size < min) { min = c.size; ret = c; } } return ret; } private ColumnNode makeDLXBoard(boolean[][] grid) { final int COLS = grid[0].length; ColumnNode headerNode = new ColumnNode("header"); List<ColumnNode> columnNodes = new ArrayList<>(); for (int i = 0; i < COLS; i++) { ColumnNode n = new ColumnNode(Integer.toString(i)); columnNodes.add(n); headerNode = (ColumnNode) headerNode.hookRight(n); } headerNode = headerNode.R.C; for (boolean[] aGrid : grid) { DancingNode prev = null; for (int j = 0; j < COLS; j++) { if (aGrid[j]) { ColumnNode col = columnNodes.get(j); DancingNode newNode = new DancingNode(col); if (prev == null) prev = newNode; col.U.hookDown(newNode); prev = prev.hookRight(newNode); col.size++; } } } headerNode.size = COLS; return headerNode; } DancingLinks(boolean[][] cover) { header = makeDLXBoard(cover); } public void runSolver() { answer = new LinkedList<>(); search(0); } private void handleSolution(List<DancingNode> answer) { int[][] result = parseBoard(answer); printSolution(result); } private int size = 9; private int[][] parseBoard(List<DancingNode> answer) { int[][] result = new int[size][size]; for (DancingNode n : answer) { DancingNode rcNode = n; int min = Integer.parseInt(rcNode.C.name); for (DancingNode tmp = n.R; tmp != n; tmp = tmp.R) { int val = Integer.parseInt(tmp.C.name); if (val < min) { min = val; rcNode = tmp; } } int ans1 = Integer.parseInt(rcNode.C.name); int ans2 = Integer.parseInt(rcNode.R.C.name); int r = ans1 / size; int c = ans1 % size; int num = (ans2 % size) + 1; result[r][c] = num; } return result; } private static void printSolution(int[][] result) { int size = result.length; for (int[] aResult : result) { StringBuilder ret = new StringBuilder(); for (int j = 0; j < size; j++) { ret.append(aResult[j]).append(" "); } System.out.println(ret); } System.out.println(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
package com.baeldung.algorithms.slope_one; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Slope One algorithm implementation */ public class SlopeOne { private static Map<Item, Map<Item, Double>> diff = new HashMap<>(); private static Map<Item, Map<Item, Integer>> freq = new HashMap<>(); private static Map<User, HashMap<Item, Double>> inputData; private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>(); public static void slopeOne(int numberOfUsers) { inputData = InputData.initializeData(numberOfUsers); System.out.println("Slope One - Before the Prediction\n"); buildDifferencesMatrix(inputData); System.out.println("\nSlope One - With Predictions\n"); predict(inputData); } /** * Based on the available data, calculate the relationships between the * items and number of occurences * * @param data * existing user data and their items' ratings */ private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) { for (HashMap<Item, Double> user : data.values()) { for (Entry<Item, Double> e : user.entrySet()) { if (!diff.containsKey(e.getKey())) { diff.put(e.getKey(), new HashMap<Item, Double>()); freq.put(e.getKey(), new HashMap<Item, Integer>()); } for (Entry<Item, Double> e2 : user.entrySet()) { int oldCount = 0; if (freq.get(e.getKey()).containsKey(e2.getKey())) { oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue(); } double oldDiff = 0.0; if (diff.get(e.getKey()).containsKey(e2.getKey())) { oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue(); } double observedDiff = e.getValue() - e2.getValue(); freq.get(e.getKey()).put(e2.getKey(), oldCount + 1); diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff); } } } for (Item j : diff.keySet()) { for (Item i : diff.get(j).keySet()) { double oldValue = diff.get(j).get(i).doubleValue(); int count = freq.get(j).get(i).intValue(); diff.get(j).put(i, oldValue / count); } } printData(data); } /** * Based on existing data predict all missing ratings. If prediction is not * possible, the value will be equal to -1 * * @param data * existing user data and their items' ratings */ private static void predict(Map<User, HashMap<Item, Double>> data) { HashMap<Item, Double> uPred = new HashMap<Item, Double>(); HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>(); for (Item j : diff.keySet()) { uFreq.put(j, 0); uPred.put(j, 0.0); } for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) { for (Item j : e.getValue().keySet()) { for (Item k : diff.keySet()) { try { double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue(); double finalValue = predictedValue * freq.get(k).get(j).intValue(); uPred.put(k, uPred.get(k) + finalValue); uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue()); } catch (NullPointerException e1) { } } } HashMap<Item, Double> clean = new HashMap<Item, Double>(); for (Item j : uPred.keySet()) { if (uFreq.get(j) > 0) { clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue()); } } for (Item j : InputData.items) { if (e.getValue().containsKey(j)) { clean.put(j, e.getValue().get(j)); } else if (!clean.containsKey(j)) { clean.put(j, -1.0); } } outputData.put(e.getKey(), clean); } printData(outputData); } private static void printData(Map<User, HashMap<Item, Double>> data) { for (User user : data.keySet()) { System.out.println(user.getUsername() + ":"); print(data.get(user)); } } private static void print(HashMap<Item, Double> hashMap) { NumberFormat formatter = new DecimalFormat("#0.000"); for (Item j : hashMap.keySet()) { System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue())); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
package com.baeldung.algorithms.slope_one; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import lombok.Data; @Data public class InputData { protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks")); public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) { Map<User, HashMap<Item, Double>> data = new HashMap<>(); HashMap<Item, Double> newUser; Set<Item> newRecommendationSet; for (int i = 0; i < numberOfUsers; i++) { newUser = new HashMap<Item, Double>(); newRecommendationSet = new HashSet<>(); for (int j = 0; j < 3; j++) { newRecommendationSet.add(items.get((int) (Math.random() * 5))); } for (Item item : newRecommendationSet) { newUser.put(item, Math.random()); } data.put(new User("User " + i), newUser); } return data; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/Item.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/Item.java
package com.baeldung.algorithms.slope_one; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Item { private String itemName; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/User.java
algorithms-modules/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/User.java
package com.baeldung.algorithms.slope_one; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class User { private String username; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false