Skip to content

Instantly share code, notes, and snippets.

@reflexdemon
Last active February 3, 2022 12:11
Show Gist options
  • Save reflexdemon/ac30249ce01638e5b9ed889b56f57bb8 to your computer and use it in GitHub Desktop.
Save reflexdemon/ac30249ce01638e5b9ed889b56f57bb8 to your computer and use it in GitHub Desktop.
This is a java program to solve a mystry number using java streams

Intresting Problem

I was suprised to see a puzzle given to an elementry school kid. Let me put the puzzle to you and I was planning to solve it manually and was lazy to do the math. Then I got an Idea to solving through Java Program. My cup of Coffee :).

Puzzle

What is the mystery number?

  1. It is greater then 1 lakh but less then 10 lakhs
  2. It's an even number
  3. None of the digits is less then 3
  4. Sum of the digits in 1s, 10s and 100s place is 12
  5. Sum of the digits in 1s, 10s and 100s place is 12

I thought Java Streams would be my best bet to solve such riddles and here is the program.

Here is the answer

687354
687534
689354
689534
786354
786534
789354
789534
986354
986534
987354
987534
import java.util.stream.IntStream;
public class SolveMathPuzzle {
public static void main(String args[]) {
IntStream.range(100000,1000000) //It is greater then 1 lakh but less then 10 lakhs
.filter(num -> num % 2 == 0 ) // It's an even number
.mapToObj(String::valueOf)
.filter(str -> str.matches("[3-9]+"))//None of the digits is less then 3
.filter(str -> str.length() == str.chars().distinct().count()) //No digits used more then once
.map(Integer::parseInt)
.filter(num -> sumd(num % 1000, 12)) //Sum of the digits in 1s, 10s and 100s place is 12
.filter(num -> sumd((num / 10) % 100, (num % 100000) / 10000)) //Sum of the digits in 1s, 10s and 100s place is 12
.forEach(System.out::println);
}
private static boolean sumd(Integer number, int value) {
int sum = String.valueOf(number).chars()
.map(c -> c-'0')
.reduce(0, Integer::sum);
return sum == value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment