-2

Hi guys please help me, i want to add names in array but without duplicacy at specific loaction. if the array has same value then it is not added into the array or vice versa Any kind of help is Appreciated.

xSkrappy
  • 747
  • 5
  • 17
Roshan jha
  • 11
  • 1
  • Please Post the code here and not in the image. Anyways , The question is already answered here. https://stackoverflow.com/questions/17967114/how-to-efficiently-remove-duplicates-from-an-array-without-using-set – xSkrappy Mar 06 '19 at 06:17
  • Actually i'm trying to using stack overflow...so i tried alot but couldn't manage in body section. it shows some error mostly code etc. – Roshan jha Mar 06 '19 at 06:19
  • but i want to do this only with the help of array no use of collection. only array – Roshan jha Mar 06 '19 at 06:22
  • Hi Roshan, and welcome to Stack Overflow (as an author)! Getting started here can sometimes be a little tricky. Please take the time and work through [ask] and perhaps some other pages of the [help]. – Florian Albrecht Mar 06 '19 at 08:12
  • Possible duplicate of [How to efficiently remove duplicates from an array without using Set](https://stackoverflow.com/questions/17967114/how-to-efficiently-remove-duplicates-from-an-array-without-using-set) – MC Emperor Mar 06 '19 at 08:49
  • @Roshanjha Please take the time to format your post properly; post your code as text instead of linking to an image. – MC Emperor Mar 06 '19 at 08:50

3 Answers3

0

Initialise arrayPosition variable to 0 in your code and try

private static int arrayPosition=0;

0

As you have not provided the language you are going to use so here is a quick algorithm to implement the solution in any language:


  1. Declare and initialize an array (Or skip it as you already have an array)
  2. iterate through an array and compare, whether the new value matches any element from an array.
  3. If it matches, break the loop
  4. If it doesn't match, append the new element to an array.
Nitinkumar
  • 19
  • 8
0

When you adding new values to array you have to consider about its widening. There are different approaches. This is most simple though voracious:

private static String[] names = new String[0];

public static void main(String[] args) {
    add("Sam");
    add("Phill");
    add("Phill");
    add("Johny");
    for (String name : names) {
        System.out.println("name = " + name);
    }
}

public static void add(String newName) {
    for (String pesentName : names) {
        if (pesentName.equals(newName)) {
            return;
        }
    }
    String[] moreNames = new String[names.length + 1];
    System.arraycopy(names, 0, moreNames, 0, names.length);
    moreNames[moreNames.length - 1] = newName;
    names = moreNames;
}

You can keep using your array but maybe you dont have to deny using collections as utills. In this case The search part will be even shorter

if (Arrays.asList(names).contains(newName)) {
        return;
    }
Ludov Dmitrii
  • 425
  • 5
  • 9