Skip to content

Commit

Permalink
Add code for pyramid word
Browse files Browse the repository at this point in the history
  • Loading branch information
ratnamal authored Oct 19, 2020
1 parent 3db508a commit faac1ef
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
2 changes: 2 additions & 0 deletions PyramidWord.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />
15 changes: 15 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.pyramid</groupId>
<artifactId>PyramidWord</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>1.5</maven.compiler.source>
<maven.compiler.target>1.5</maven.compiler.target>
</properties>
</project>
57 changes: 57 additions & 0 deletions src/main/java/com/pyramid/PyramidWord.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.pyramid;

import java.util.*;

public class PyramidWord {

//checks if a input string is a pyramid word
//Returns "true" if the input string is a pyramid word else false
static boolean checkPyramid(String str) {

//check if string length is 1
if(str.length() == 1)
return true;

//Move each character from the input string and it's frequency to a hash map
HashMap<Character,Integer> m = new HashMap<Character, Integer>();
for(int i=0;i< str.length();i++) {
if(m.containsKey(str.charAt(i))) {
m.put(str.charAt(i), m.get(str.charAt(i)) + 1);
}
else {
m.put(str.charAt(i), 1);
}
}

//Sort the Hash Map based on frequencies
List<Map.Entry<Character,Integer>> entryList = new LinkedList<Map.Entry<Character, Integer>>(m.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});

//Check for increasing frequencies
int count=2;
for(Map.Entry<Character,Integer> map: entryList) {
if(map.getValue()+1 == count) {
count++;
}
else
return false;
}

return true;
}

public static void main(String[] args) {
//enter an input string
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

if(checkPyramid(input))
System.out.println("Word is a pyramid word");
else
System.out.println("Word is not a pyramid word");
}
}

0 comments on commit faac1ef

Please sign in to comment.