How to Check if Two Words are Anagrams in Java

Permutations of a word are generated by shuffling the letters in the word. The full set consists of all permutations of the letters in a word. However only a subset of these are valid words in English language. These valid word combinations of letters is known as the Anagram for the original word and vice versa.

To verify whether two words are anagrams of each other we need to check whether they are the permutations of the same letter set and also whether they are valid words. However checking the second part is complex and requires access to the entire English dictionary. The following Java program only verifies that the given strings are permutations of the same set of letters.

Given two words for comparison, we first remove all the spaces and then convert the strings to lowercase for case insensitive comparison. We then convert each string to a character array and then sort it alphabetically. If the sorted character arrays are same we know that the words are anagrams of each other.

Java Program to Check Whether Two Words are Anagrams of Each Other

import java.util.Arrays;
import java.util.Scanner;

// Checks whether two words are anagrams of each other in Java
public class AnagramChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please enter the first word: ");
        String word1 = scanner.nextLine();
        
        System.out.print("Please enter the second word: ");
        String word2 = scanner.nextLine();
        
        if(isAnagram(word1,word2)) {
            System.out.println(word1+" is an anagram of "+word2);
        }else {
            System.out.println(word1+" is NOT an anagram of "+word2);
        }

        scanner.close();
    }

    // Check if two words are anagrams in Java
    // Uses sorting and comparison of character arrays
    private static boolean isAnagram(String word1, String word2) {
       word1 = word1.replaceAll("\\s", "").toLowerCase();
       word2 = word2.replaceAll("\\s", "").toLowerCase();
       
       char[] word1Arr = word1.toCharArray();
       char[] word2Arr = word2.toCharArray();
       
       Arrays.sort(word1Arr);
       Arrays.sort(word2Arr);
       
       return (Arrays.equals(word1Arr, word2Arr));
    }
}

Following is a sample run of the above program,

java AnagramChecker
Please enter the first word: Eleven plus two
Please enter the second word: Twelve plus one
Eleven plus two is an anagram of Twelve plus one

Following is alternate implementation for checking whether two words are anagrams. We iterate through the letters of the first word removing each letter from the second word. Finally if there are no letters remaining in the second word we know that both are anagrams of each other.

import java.util.Arrays;
import java.util.Scanner;

//Checks whether two words are anagrams of each other in Java
public class AnagramChecker2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please enter the first word: ");
        String word1 = scanner.nextLine();
        
        System.out.print("Please enter the second word: ");
        String word2 = scanner.nextLine();
        
        if(isAnagram(word1,word2)) {
            System.out.println(word1+" is an anagram of "+word2);
        }else {
            System.out.println(word1+" is NOT an anagram of "+word2);
        }

        scanner.close();
    }

    // Check if two words are anagrams in Java
    // Removes letters in word1 from word2. 
    // If there are no letters left in word2, we know that they are anagrams of each other
    private static boolean isAnagram(String word1, String word2) {
       word1 = word1.replaceAll("\\s", "").toLowerCase();
       word2 = word2.replaceAll("\\s", "").toLowerCase();
       
       // Length of two strings must match!
       if(word1.length()!=word2.length()) {
           return false;
       }
       
       for(int i=0;i<word1.length();i++) {
           // Is there a letter in word2 corresponding to the word1 letter?
           int pos = word2.indexOf(word1.substring(i, i+1));
           if(pos>=0) {
               // Remove the letter!
               word2 = word2.substring(0, pos)+word2.substring(pos+1);
           }else {
               // Letter not found! Hence not an anagram
               return false;
           }
       }
       
       // Finally if word2 is empty, it is an anagram of word1
       if(word2.length()==0) {
           return true;
       }else {
           return false;
       }
    }
    
}

How to Find Sum of Digits of a Number in Java

The following Java program computes the sum of digits of a number. For example, if the input is 278, the output is calculated as 2+7+8 = 17. This function is useful in a number of numeric algorithms. For example,  IMEI check sum algorithm requires calculation of sum of digits. This problem is also given as an exercise for beginners in Java programming.

Algorithm for Finding Sum of Digits of a Number

We start by dividing the number with 10 and finding the remainder. The following program uses Java modulus operator for this. This gives us the right most digit. We then divide the number by 10 to remove the right most digit. This process is repeated until no more digits are left in the number. Each digit we extract is added to a separate variable to compute the sum.

Java Source Code for Finding Sum of Digits of a Number

The following Java program uses only core Java APIs.

import java.util.Scanner;

// Java program to find sum of digits of a number
public class SumOfDigitsInJava {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please a number: ");
        int number = scanner.nextInt();

        int sumOfDigits = findSumOfDigits(number);
        System.out.println("Sum of digits of " + number + " is " + sumOfDigits);

        scanner.close();
    }

    // Find sum of digits of a number
    public static int findSumOfDigits(int number) {
        int sum = 0;
        while (number > 0) {
            int digit = number % 10;
            number = number / 10;
            sum += digit;
        }
        return sum;
    }
}

Here is a sample output of the above Java program,

java SumOfDigitsInJava
Please a number: 278
Sum of digits of 278 is 17

Spring Boot Quartz Scheduler Integration

Configuring quartz scheduler in a spring boot application requires a number of steps. This tutorial assumes that you already have a simple spring boot application up and running. Please see this tutorial on developing spring boot applications with spring tool suite if you are not familiar with setting up a simple spring boot application.

The following example uses RAMJobStore for persisting quartz job. This is one of fastest jobstore implementations for storing quartz job schedules. RAMJobStore stores quartz job data in the memory and hence scheduling information is lost in case of a program crash. This may not be suitable for all use cases. However, we will use RAMJobStore in this tutorial to keep the configuration simple.

Step 1: Modify the build.gradle to add quartz and related dependencies. Please refer to the updated gradle file below for the dependency details,

1. build.gradle

buildscript {
    ext {
        springBootVersion = '1.5.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework:spring-context-support')
    compile('org.springframework:spring-tx')
    compile('org.quartz-scheduler:quartz:2.2.1')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Step 2: Write the classes for the schedule job and the underlying application service. Following is a simple spring service used by the tutorial. It prints "Hello World!" in the console log. We will also write a quartz job to invoke this service.

2a. SimpleService.java

package com.quickprogrammingtips.springboot.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class SimpleService {
    private static final Logger LOG = LoggerFactory.getLogger(SimpleService.class);

    public void processData() {
        LOG.info("Hello World!");
    }
}

2b. SimpleJob.java

package com.quickprogrammingtips.springboot.jobs;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.quickprogrammingtips.springboot.services.SimpleService;

public class SimpleJob implements Job{

    @Autowired
    private SimpleService service;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        service.processData();
    }
}

Step 3: Create a custom SpringBeanJobFactory for enabling spring auto wiring for the SimpleJob and SimpleService written above. This is required because SpringBeanJobFactory manually instantiates job instances whenever a job needs to run. Hence spring autowiring needs to be manually applied on the job instance if we are using autowiring features in the classes invoked by job instance (SimpleJob and SimpleService above).

3. AutowiringSpringBeanJobFactory.java

package com.quickprogrammingtips.springboot;

import org.quartz.spi.TriggerFiredBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

    private static final Logger LOG = LoggerFactory.getLogger(AutowiringSpringBeanJobFactory.class);

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        LOG.info("create job instance");
        beanFactory.autowireBean(job);
        return job;
    }
}

Step 4: Create a spring bean java configuration class for configuring all the beans required for the quartz scheduler. We configure a job factory using the custom AutowiringSpringBeanJobFactory created above. We also setup the quartz scheduler using the SchedulerFactoryBean. Note how the SimpleJob is configured using JobDetailFactoryBean and SimpleTriggerFactoryBean.  The quartz configuration is loaded from the quartz.properties in classpath. The frequency of job is configured using the spring property simplejob.frequency. We will set this value in application.properties.

4. SchedulerConfig.java

import java.io.IOException;
import java.util.Properties;

import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.spi.JobFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

import com.quickprogrammingtips.springboot.jobs.SimpleJob;

@Configuration
public class SchedulerConfig {

    private static final Logger LOG = LoggerFactory.getLogger(SchedulerConfig.class);

    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, Trigger simpleJobTrigger)
            throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setJobFactory(jobFactory);
        factory.setQuartzProperties(quartzProperties());
        factory.setTriggers(simpleJobTrigger);
        LOG.info("starting jobs....");
        return factory;
    }

    @Bean
    public SimpleTriggerFactoryBean simpleJobTrigger(@Qualifier("simpleJobDetail") JobDetail jobDetail,
            @Value("${simplejob.frequency}") long frequency) {
        LOG.info("simpleJobTrigger");

        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetail);
        factoryBean.setStartDelay(0L);
        factoryBean.setRepeatInterval(frequency);
        factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        return factoryBean;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    @Bean
    public JobDetailFactoryBean simpleJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(SimpleJob.class);
        factoryBean.setDurability(true);
        return factoryBean;
    }
}

Step 5: Modify the main spring boot application to load the SchedulerConfig.

5. SpringbootquartzdemoApplication

package com.quickprogrammingtips.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

@Import({ SchedulerConfig.class })
@SpringBootApplication
public class SpringbootquartzdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootquartzdemoApplication.class, args);
    }
}

Step 6: Configure application.properties with simplejob.frequency entry. We set the job running every second!

6. application.properties

simplejob.frequency=1000

Step 7: Configure quartz.propertes with minimal quartz configuration.

7. quartz.properties

org.quartz.scheduler.instanceName=spring-boot-quartz-demo
org.quartz.scheduler.instanceId=AUTO
org.quartz.threadPool.threadCount=5
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore

Step 8: Run the application using the gradle bootRun task. If everything goes well, "Hello World!" will be printed on the console every second.

Fascinating Number in Java

What is a Fascinating Number?

Fascinating numbers are 3 digit numbers with a unique property. When a 3 digit number is concatenated with the number multiplied by 2 and the number multiplied by 3, sometimes we get a number which contains all the digits from 1 to 9 exactly once. There could be any number of zeros, but they are ignored. Such a 3 digit number is known as a fascinating number.

Let us look at an example. Consider the number 273. Following are the multiples of 2 and 3 of the number 273.

  • 1 x 273 = 273
  • 2 x 273 = 546
  • 3 x 273 = 819

Concatenating all the numbers, we get the final number 273546819. This is a fascinating number since it contains all the digits 1 to 9 exactly once!

Problem: Find whether a given number is a fascinating number using Java

The following Java program checks whether a given 3 digit number is a fascinating number. The Java program concatenates the given number with its multiples of 2 and 3. Then it checks whether the resulting number contains 1 to 9 exactly once. There could be any number of zeros and they are ignored.

import java.util.Scanner;

// Java program to check for fascinating numbers
public class CheckFascinatingNumber {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter a 3 digit number: ");
        int number = scanner.nextInt();

        if (number < 100 || number > 999) {
            System.out.println(number + " is not a valid 3 digit number!");
        } else {
            if (isFascinatingNumber(number)) {
                System.out.println(number + " is a fascinating number!");
            } else {
                System.out.println(number + " is NOT a fascinating number!");
            }
        }

        scanner.close();
    }

    // Checks whether the input number is a fascinating number
    public static boolean isFascinatingNumber(int input) {
        String sVal = "" + input + input * 2 + input * 3;

        // check existence of 1 to 9 exactly once!
        for (int i = 1; i <= 9; i++) {
            int pos = sVal.indexOf(i + "");
            // is digit missing?
            if (pos < 0) {
                return false;
            } else {
                // Is there a duplicate digit?
                if (sVal.substring(pos+1).indexOf(i + "") >= 0) {
                    return false;
                }
            }

        }
        System.out.println(sVal);
        return true;
    }

}

Following is the sample output from the above program,

java CheckFascinatingNumber
Please enter a 3 digit number: 273
273546819
273 is a fascinating number!

Problem: Find all fascinating numbers using Java

The following Java program uses the logic written in the above program to find all 3 digit fascinating numbers. The program iterates from 100 to 999 looking for fascinating numbers.

// Java example source code for fascinating number
// Generates all 3 digit fascinating numbers using Java
public class FascinatingNumberGenerator {

    public static void main(String[] args) {
        System.out.println("Generating all 3 digit fascinating numbers!");
        for(int i=100;i<=999;i++) {
            if(isFascinatingNumber(i)) {
                System.out.print(i+", ");
            }
        }
    }
    
    // Checks whether the input number is a fascinating number
    public static boolean isFascinatingNumber(int input) {
        String sVal = "" + input + input * 2 + input * 3;

        // check existence of 1 to 9 exactly once!
        for (int i = 1; i <= 9; i++) {
            int pos = sVal.indexOf(i + "");
            // is digit missing?
            if (pos < 0) {
                return false;
            } else {
                // Is there a duplicate digit?
                if (sVal.substring(pos+1).indexOf(i + "") >= 0) {
                    return false;
                }
            }

        }
        return true;
    }
}

Following is the output of the above program. It shows that there are exactly four 3 digit fascinating numbers!

java FascinatingNumberGenerator
Generating all 3 digit fascinating numbers!
192, 219, 273, 327,

Keith Number Program in Java

Keith numbers are rare numbers with a Fibonacci like property. An n-digit number with value N is a Keith number if N is part of the Keith series generated. This series starts with the n digits of the number N. Then the subsequent numbers in the series are found by calculating the sum of preceding n numbers. If the number N appears in the series, it is called a Keith number. Keith numbers are also known as repfigit (repetitive Fibonacci-like digit) numbers. Keith numbers are very rare and computationally difficult to find. No optimized algorithm is known for finding Keith numbers. Only option is to do an exhaustive search.

For example consider the 3 digit number 742. Using the above rule, the first three numbers are 7, 4, 2. The next one is 7+4+2 (adding 3 previous numbers) = 13. The next one in series is 4+2+13 = 19. By applying this rule, following are numbers in the sequence,

7, 4, 2, 13, 19, 34, 66, 119, 219, 404, 742, 1365. The original number appears as the 11th item in the series. Hence the number 742 is a 3 digit Keith number.

Problem: Find whether a given number is a keith number using Java

The following Java program first extracts the individual digits in the number. It then computes the series using the sum of n previous numbers where n is the number of digits. If one of the numbers computed in the series is same as the input number, it is a keith number. The program stops if the value computed is bigger than the input number.

import java.util.Scanner;

// Java example - Find whether a number is a Keith number
public class KeithNumberChecker {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter a number: ");

        String input = scanner.nextLine();

        // Keith numbers must be > 10
        if (input.length() > 1 && isKeithNumber(input)) {
            System.out.println(input + " is a Keith number!");
        } else {
            System.out.println(input + " is NOT a Keith number!");
        }

        scanner.close();

    }

    // Checks whether input number is a Keith number
    public static boolean isKeithNumber(String input) {
        int len = input.length();
        // we keep only last n elements of the series
        long[] series = new long[len];

        for (int i = 0; i < len; i++) {
            series[i] = Long.valueOf(input.substring(i, i + 1));
        }
        long next = 0;
        long number = Long.valueOf(input);

        while (next < number) {
            next = 0;
            for (int i = 0; i < len; i++) {
                next += series[i];
                if (i < len - 1) {
                    series[i] = series[i + 1]; // shift series to left
                } else {
                    series[i] = next; // add new value to the series
                }
            }
            if (next == number) {
                return true;
            }
        }
        return false;
    }
}

Following is the sample output from the program,

java KeithNumberChecker
Please enter a number: 197
197 is a Keith number!

Problem: Find all n-digit keith numbers using Java

The following Java program finds all n-digit keith numbers. It starts with the lowest n-digit number (10 raised to n) and checks all numbers till the largest n-digit number. For large numbers, this program can be very slow,

import java.util.Scanner;

// Java source code for Keith number generator
// Find all n-digit keith numbers in Java
public class FindKeithNumbersInJava {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("How many digits required in Keith number? ");

        int len = scanner.nextInt();

        if (len < 2) {
            System.out.println("Keith numbers require minimum 2 digits");
        } else {

            long lowBound = (long) Math.pow(10, len - 1);
            long upperBound = (long) Math.pow(10, len);

            for (long l = lowBound; l < upperBound; l++) {
                if (isKeithNumber(String.valueOf(l))) {
                    System.out.print(l + ", ");
                }
            }
        }
        scanner.close();
    }

    // Checks whether input number is a Keith number
    public static boolean isKeithNumber(String input) {
        int len = input.length();
        // we keep only last n elements of the series
        long[] series = new long[len];

        for (int i = 0; i < len; i++) {
            series[i] = Long.valueOf(input.substring(i, i + 1));
        }
        long next = 0;
        long number = Long.valueOf(input);

        while (next < number) {
            next = 0;
            for (int i = 0; i < len; i++) {
                next += series[i];
                if (i < len - 1) {
                    series[i] = series[i + 1]; // shift series to left
                } else {
                    series[i] = next; // add new value to the series
                }
            }
            if (next == number) {
                return true;
            }
        }
        return false;
    }
}

Following is the sample output from the program,

java FindKeithNumbersInJava
How many digits required in Keith number? 5
31331, 34285, 34348, 55604, 62662, 86935, 93993,

Problem: Find first n keith numbers using Java

The following java program finds first n Keith numbers. The program starts iteration from number 10 till n values are found. Please note that if you try to generate more than first 40 Keith numbers, the program may take a while to execute.

import java.util.Scanner;

// Find the first n keith numbers in Java
public class KeithNumberGenerator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("How many keith numbers do you want? ");

        int size = scanner.nextInt();
        int counter = 0;
        for (long l = 10; l < Long.MAX_VALUE; l++) {
            if (isKeithNumber(String.valueOf(l))) {
                System.out.print(l + ", ");
                counter++;
                if(counter==size) {
                    break;
                }
            }
        }
        scanner.close();
    }

    // Checks whether input number is a Keith number
    public static boolean isKeithNumber(String input) {
        int len = input.length();
        // we keep only last n elements of the series
        long[] series = new long[len];

        for (int i = 0; i < len; i++) {
            series[i] = Long.valueOf(input.substring(i, i + 1));
        }
        long next = 0;
        long number = Long.valueOf(input);

        while (next < number) {
            next = 0;
            for (int i = 0; i < len; i++) {
                next += series[i];
                if (i < len - 1) {
                    series[i] = series[i + 1]; // shift series to left
                } else {
                    series[i] = next; // add new value to the series
                }
            }
            if (next == number) {
                return true;
            }
        }
        return false;
    }
}

Following is the sample output from the program,

java KeithNumberGenerator
How many keith numbers do you want? 10
14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537,