Find Pairs of Nuts and Bolts in Minimum Number of Iteration

package org.wesome.dsalgo;
// Hashmap based solution to solve

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

class NutBolt {
    static void matchNutBolt(char nuts[], char bolts[]) {
        System.out.println("nuts = " + Arrays.toString(nuts));
        System.out.println("bolts = " + Arrays.toString(bolts));
        Set<Character> nutBoltSet = new HashSet<>();
        int size = Math.min(nuts.length, bolts.length);
        /*  Add nuts into set   */
        for (int i = 0; i < size; i++) {
            nutBoltSet.add(nuts[i]);
        }
        /*if set contains bolt, then */
        for (int i = 0; i < size; i++) {
            if (nutBoltSet.contains(bolts[i])) {
                nuts[i] = bolts[i];
            }
        }

        System.out.println("nuts with matching bolts");
        for (int i = 0; i < size; i++) {
            System.out.println("nuts - " + nuts[i] + " bolt - " + bolts[i]);
        }
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.NutBolt.matchNutBolt;

public class NutBoltTest {
    @Test
    void matchNutBoltTest1() {
        char nuts[] = {'!', '@', '#', '$', '%', '^', '&'};
        char bolts[] = {'$', '%', '&', '^', '@', '#', '!'};
        matchNutBolt(nuts, bolts);
    }

    @Test
    void matchNutBoltTest2() {
        char nuts[] = {'@', '#', '$', '%', '!', '^', '&', '*'};
        char bolts[] = {'$', '%', '&', '^', '@', '!', '#'};
        matchNutBolt(nuts, bolts);
    }

    @Test
    void matchNutBoltTest3() {
        char nuts[] = {'@', '#', '$', '%', '^', '&', '!',};
        char bolts[] = {'$', '%', '&', '^', '@', '#', '!', '*'};
        matchNutBolt(nuts, bolts);
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on