Created
July 16, 2023 03:05
-
-
Save donal56/7c9aa70d667e02890d34299fbcc17954 to your computer and use it in GitHub Desktop.
Various Code Tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mx.com.insigniait.scriptum.controllers; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
/** | |
* @author Doni, 10/07/2023 10:10:21 | |
* | |
*/ | |
public class TestClass { | |
public static void main(String[] args) { | |
System.out.println("isAnagram= " + isAnagram(4280, 7024)); | |
} | |
/** | |
* Checks if a number is an anagram of another | |
* @param i | |
* @param j | |
*/ | |
private static boolean isAnagram(int number1, int number2) { | |
String word1 = Integer.toString(number1); | |
String word2 = Integer.toString(number2); | |
if(word1.length() != word2.length()) return false; | |
for(int i = 0; i < word1.length(); i++) { | |
char currentChar = word1.charAt(i); | |
int indexOfLetter = word2.indexOf(currentChar); | |
if(indexOfLetter == -1) return false; | |
StringBuilder sb = new StringBuilder(word2); | |
sb.deleteCharAt(indexOfLetter); | |
word2 = sb.toString(); | |
} | |
return word2.length() == 0; | |
} | |
/** | |
* Swaps without using a third variable | |
* @param x | |
* @param y | |
*/ | |
public static void swapNumbers(int x, int y) { | |
// For y = 5, x = 3 | |
y = y + x; // y = 8 | |
x = y - x; // x = 5 | |
y = y - x; // y = 3 | |
System.out.println("x= " + x); | |
System.out.println("y= " + y); | |
} | |
/** | |
* Sums the non-repeated numbers from an array | |
* @param numbers | |
*/ | |
public static void sumNonRepeatedNumbers(List<Integer> numbers) { | |
Integer sum = numbers | |
.stream() | |
.collect(Collectors.groupingBy(Function.identity())) | |
.entrySet() | |
.stream() | |
.filter(x -> x.getValue().size() == 1) | |
.map(x -> x.getKey()) | |
.reduce((el, acc) -> acc + el) | |
.orElse(0); | |
System.out.println(sum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment