is this the best anagram checking solution? - anagram

I am looking for an efficient solution to check if two strings are anagrams, but char table/dictionary checking may not be a good solution for unicode. I have come up a solution, but I don't know how to prove it mathematically correct. The formula is in the express as " (a + b) = (c + d) and a XOR b XOR c XOR d = 0 ==> (a,b) and (c,d) are anagrams". Maybe you can help me. The following is an implementation.
def isAnagram(s1: String, s2: String): Boolean = {
if (s1.length != s2.length) return false
else {
var numVal = 0
var bitVal = 0
for (i <- 0 until s1.length) {
numVal += s1(i) - s2(i)
bitVal ^= s1(i) ^ s2(i)
}
return numVal == 0 && bitVal == 0
}

icepack's counter example is incorrect, as 1 ^ 5 ^ 3 ^ 2 ^ 4 ^ 3 = 2, not 0.
Here's a better counter example: s1 = (5, 0, 5) and s2 = (1, 4, 5).
5 + 0 + 5 = 1 + 4 + 5
5 ^ 0 ^ 5 ^ 1 ^ 4 ^ 5 = 0

Your conditions aren't good enough.
Here is an opposite example:
s1 = (1,5,3), s2 = (2,4,3)
1+5+3=9=2+4+3
1 ^ 5 ^ 3 ^ 2 ^ 4 ^ 3 = 0

This is one of the easiest way to find two strings are anagram or not.
<?php
$str1=$_POST['str1'];
$str2=$_POST['str2'];
$arr1=str_split($str1);
$arr2=str_split($str2);
sort($arr1);
sort($arr2);
echo (($arr1==$arr2) ? "The given string is anagram" : "The given string is not a anagram");
}
?>

import java.util.Arrays;
import java.util.Scanner;
public class anagram {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter 1st String");
String r1=sc.nextLine();
System.out.println("Enter 2nd String");
String r2=sc.nextLine();
if(r1.length()!=r2.length()) System.out.println("not a Anagram");
char[] s1=r1.toCharArray();
char[] s2=r2.toCharArray();
Arrays.sort(s1);
Arrays.sort(s2);
boolean f= Arrays.equals(s1, s2);
if(f==false) System.out.println("not a Anagram");
else System.out.println("its a Anagram");
}
}

Related

print n times number from 1. Need print (1 2 2 3 3 3 4)

I can't figure out how to solve the following problem: there is a number n. Output the numbers to the console in order separated by a space, but so that the next digit in the iteration is output as many times as it is a digit, and at the same time so that there are no more than n digits in the output. Сan anyone suggest the correct algorithm?
example: have n = 7, need print (1 2 2 3 3 3 4) in kotlin
what i try:
var n = 7
var count = 1
var i = 1
for (count in 1..n) {
for (i in 1..count) {
print(count)
}
}
}
var n = 11
var count = 1
var i = 1
var size = 0
// loop# for naming a loop in kotlin and inside another loop we can break or continue from outer loop
loop# for (count in 1..n) {
for (i in 1..count) {
print(count)
size++
if (size == n){
break#loop
}
}
}
You can use "#" for naming loops and if you want to break from that loop, you can use this syntax in kotlin. It worked for me.
For kotlin labeled break you can look at this reference: link
var count = 1
var n = 7
for(count in 1..n) {
print(count.toString().repeat(count))
}
count.toString() converts an integer to a string, .repeat() function repeats count times the string.
In case you need to add a space between each number, you can add the following:
print(" ")
Using generateSequence and Collections functions:
val n = 7
println(generateSequence(1) {it + 1}
.flatMap{e -> List(e){e}}
.take(n)
.joinToString(" "))
Your example is correct, You have to put a space between the printing
you can follow the code from this link
Kotlin lang code snippet
or the following code snippet
fun main() {
var n = 7
var count = 1
var i = 1
for (count in 1..n) {
for (i in 1..count) {
print(count)
print(' ')
}
}
}
For completeness, here's another approach where you write your own sequence function which produces individual values on demand (instead of creating intermediate lists)
sequence {
var digit = 1
while (true) {
for (i in 1..digit) yield(digit)
digit++
}
}.take(7)
.joinToString(" ")
.run(::print)
Not a big deal in this situation, but good to know!

Given an integer array A of size N. Find the sum of GCD (Greatest Common Divisor) of all elements with their frequency (In JAVA)

Problem Statement
Given an integer array A of size N. Find the sum of GCD (Greatest Common Divisor) of all elements with their frequency.
Input
First line contains an integers N.
Next line contains N space separated integers denoting elements of array.
Constraints
1 <= N <= 1000
0 <= Ai<= 10^5
Output
Print the sum of GCD of all elements with their frequency.
Example
Sample Input 1:
3
1 2 3
Output
3
Explanation:
gcd(1, 1) + gcd(2, 1) + gcd(3, 1) = 1+1+1 = 3
Sample Input 2:
6
3 6 6 9 3 3
Output
14
Explanation
gcd(3, 3) + gcd(6, 2) + gcd(6, 2) + gcd(9, 1) + gcd(3, 3) + gcd(3, 3)= 3+2+2+1+3+3= 14
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
class Main {
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
int N = s.nextInt();
int [] a= new int[N];
HashMap<Integer,Integer> map = new HashMap<>();
for (int i=0;i<N;i++) {
a[i]=s.nextInt();
map.put(a[i],map.getOrDefault(a[i],0)+1);
}
long sum=0;
for (int i=0;i<N;i++) {
sum += gcd(a[i],map.get(a[i]));
}
System.out.println(sum);
}
public static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b,a%b);
}
}

Kotlin. Function does not exit recursion after return

I need to decompose the number l into prime factors. For this I use recursion. And when l = 1, the function must exit their recursion and return the string in which the prime factors are located, however, the function continues to work and already according to a principle incomprehensible to me. Please explain what is the problem with my code?
fun factors(l: Int): String {
return if (l == 1) {
answer
} else {
for (i in 2..l) {
if (l % i == 0) {
answer += "$i "
factors(l / i)
}
}
return factors(l)
}
}
Let's first mention some issues in your current code:
You're mixing semantics, here. What is the contract of your function? Does it return a value, or does it modify a global variable? Pick one, don't do both.
You should not use a global variable because it's way harder to follow. Instead, construct your values locally from the current information + whatever the recursive call returns to you
You're already using an if expression with the syntax return if (condition) { ... } else { ... }. This means each branch of the if should just end with an expression, you don't need to use return again. That said, in this case the first branch is rather a special case that you want to get out of the way before doing the bulk of the general work. In this kind of situation, I would rather use a statement like if (condition) { return X } at the beginning and then have the rest of the body of the function unnested, instead of using an if expression (but that is a personal preference).
It is strange to compute the list of factors as a string. You likely want to avoid duplicates and maybe sort them, so a List<Int> or a Set<Int> would likely be more appropriate. You can always format after the fact using things like joinToString(" ")
I'm not sure I get the math correctly, but it seems you really will be getting all factors here, not just the prime factors.
Now, the actual cause of the behaviour you're seeing is that you're calling your function recursively with the same number at the end: return factors(l). This means that calling factors(l) with any l > 1 will end up calling itself with the same value over and over. Recursive calls need to change some arguments to the function if you don't want it to be infinite.
fun factors(value: Int, list: MutableList<Int> = mutableListOf()): MutableList<Int> {
if (value > 1) {
for (i in 2..value) {
if (value % i == 0) {
list.add(i)
list.addAll(factors(value / i))
break
}
}
}
return list
}
(2..25).forEach {
val factors = factors(it)
val result = factors.reduce { acc, i -> acc * i }.toString() + " = " + factors.joinToString(" × ")
println(result)
}
Edit: this version is based on #Joffrey's comment below. Plus I decided to wrap the recursive function, now called fn, into a function in order to have a clean parameter list for factors():
fun factors(value: Int): List<Int> {
fun fn(value: Int, list: MutableList<Int>) {
if (value > 1) {
for (i in 2..value) {
if (value % i == 0) {
list.add(i)
fn(value / i, list)
break
}
}
}
}
val list = mutableListOf<Int>()
fn(value, list)
return list
}
Output:
2 = 2
3 = 3
4 = 2 × 2
5 = 5
6 = 2 × 3
7 = 7
8 = 2 × 2 × 2
9 = 3 × 3
10 = 2 × 5
11 = 11
12 = 2 × 2 × 3
13 = 13
14 = 2 × 7
15 = 3 × 5
16 = 2 × 2 × 2 × 2
17 = 17
18 = 2 × 3 × 3
19 = 19
20 = 2 × 2 × 5
21 = 3 × 7
22 = 2 × 11
23 = 23
24 = 2 × 2 × 2 × 3
25 = 5 × 5

Valid Triangle: Error getting sum of two sides less then the third?

Getting wrong output While trying to check the validity of a triangle where condition is ** sum of two side should be greater then the third** on 3 random integers between 0 to 20. Below output suggest two sides are greater then the third but showing "Not a valid triangle".
fun main() {
var a = (Math.random() * 20).toInt()
var b = (Math.random() * 20).toInt()
var c = (Math.random() * 20).toInt()
var validTriangle = "length $a,$b,$c"
if (a + b > c && b + c > a && a + c > b) {
println("Valid Triangle")
} else {
println("Not a valid Triangle")
}
println(validTriangle)
The below output suggests sum of two side(13,6) should be > third side(4)
which is 19 so answer should be "valid triangle" but it is not showing that
Output:
Not a valid Triangle
length 13,6,4

How can I know whether one number is a multiple of other number?

I tried using 6%2, but its always giving the value as 2 and not 0. Why and how can I get a solution to this?
if(!(y%x))
{
...
}
In your case !(6%2) would return true.
(Answer very similar to the original in the question)
I'm asuming that you want to find out if Y=kX has integer values of k for a given X so that Y=5, X=3 fails (k is 5/3), but Y=6, X=2 passes (k is exactly 3). You are happy that k is either positive or negative.
That way, using Y remainder X == 0 is a good test. As an aside, be careful of negative remainders (e.g. Y % 2 == 1 as a test for oddness fails for negative numbers, use Y % 2 != 0 to be sure)
Code example in Java
public class Example {
public static void main(String[] args) {
System.out.println(isIntegerFactor(5,3)); // k is not an integer
System.out.println(isIntegerFactor(6,3)); // k is 2
System.out.println(isIntegerFactor(-6,-3)); // k is 2
System.out.println(isIntegerFactor(-6,3)); // k is -2
System.out.println(isIntegerFactor(6,-3)); // k is -2
}
public static boolean isIntegerFactor(int y, int x) {
return (y % x) == 0;
}
}
bool prime = PrimeTool.IsPrime(input_Number);
if (!prime)
{
Console.Write("multiple of other number");
Console.WriteLine(i);
}