You are given two int variables j and k, an int array zipcodeList that has been declared and initialized, an int variable nZips that contains the number of elements in zipcodeList, and a bool variable duplicates. Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise. Use only j, k, zipcodeList, nZips, and duplicates.

7
You are given two int variables j and k, an int array zipcodeList that has been declared and initialized, an int variable nZips that contains the number of elements in zipcodeList, and a bool variable duplicates. Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise. Use only j, k, zipcodeList, nZips, and duplicates.

LANGUAGE: C++

CHALLENGE:

You are given two int variables j and k, an int array zipcodeList that has been declared and initialized, an int variable nZips that contains the number of elements in zipcodeList, and a bool variable duplicates. Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise. Use only j, k, zipcodeList, nZips, and duplicates.

SOLUTION:


duplicates = false;
for (k =0; k < nZips; k++){
    for(j=k+1 ;j<nZips;j++){
        if (zipcodeList[k] == zipcodeList[j]){
            duplicates = true;
            break;
        }
    }
}

7 comments

  • darren says:

    Won’t this code always result in duplicates = true? Since the first element that’s being compared is

    zipcodeList[0] == zipcodeList[0]

    codelabs accepts the answer, but I’m not understanding it. Thanks for all your help posting these answers btw!

  • RJ says:

    You cant use j =0… you have to use j = k+1, otherwise j =1 and k =1 will match up and be equal when really its comparing the exact same line to itself.

    This is what I used that finally worked.

    duplicates = false;
    for (k =0; k < nZips; k++)
    {

    for(j=k+1 ;j<nZips;j++)
    {

    if (zipcodeList[k] == zipcodeList[j])
    {
    duplicates = true;
    break;

    }

    }

    }

  • No Comprende says:

    Correct Answer:

    duplicates = false;

    for(k = 0; k < zipcodeList.length; k++) {

    for(j = k+1; j < zipcodeList.length; j++) {
    if(zipcodeList[j] == zipcodeList[k]) {
    duplicates = true;
    break;
    }

    }
    }

  • No Comprende says:

    Correct Answer for Java:

    duplicates = false;

    for(k = 0; k < zipcodeList.length; k++) {

    for(j = k+1; j < zipcodeList.length; j++) {
    if(zipcodeList[j] == zipcodeList[k]) {
    duplicates = true;
    break;
    }

    }
    }

  • hotrodjeremy says:

    duplicates=false;
    for (k = 0; k < zipcodeList.length; k++)
    for (j = 0; j < k; j++)
    {
    if ( zipcodeList[j] == zipcodeList[k])
    {
    duplicates=true;
    break;
    }
    }

Add comment