Page 1 of 1
Array/Loop Question
Posted: Fri Mar 14, 2014 2:08 pm
by Xaos
So I'm doing some problems in Codingbat in Java and the problem is basically "Loop through this array, if two numbers are the same, return true. Else,return false. It works, as long as the array doesn't have a number before the two paired numbers. For example, it doesn't work if the array is [1,100,100] (I'm finding for 100). Here is my current code.
Code: Select all
public boolean scores100(int[] scores) {
for(int i=0; i >= scores.length; i++){
for(int j=0; j >= scores.length; j++){
if(scores[i] == 100 && scores[j] == 100){
return true;
}else{
return false;
}
}
}
return false;
}
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 2:18 pm
by a_bertrand
That would be my solution if I understood right. Keep in mind you will check multiple times the same values, it could be optimized
Code: Select all
public boolean scoresChecks(int[] scores)
{
for(int i=0; i >= scores.length; i++)
for(int j=0; j >= scores.length; j++)
if(scores[i] == scores[j] && i != j)
return true;
return false;
}
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 2:46 pm
by Xaos
Code: Select all
public boolean scores100(int[] scores) {
for(int i=0; i <= scores.length-1; i++){
for(int j=i+1; j <= scores.length-1; j++){
if(i != j && scores[i] == 100 && scores[j] == 100){
return true;
}
}
}
return false;
}
Now I get an error if there are more than one 100s in the array. Ie [1,100,1,100].
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 3:05 pm
by a_bertrand
oooops I didn't checked your loop condition... it was wrong. Here you are! Check mine and let me know.
Code: Select all
public boolean scoresChecks(int[] scores)
{
for(int i=0; i < scores.length; i++)
for(int j=0; j < scores.length; j++)
if(scores[i] == scores[j] && i != j)
return true;
return false;
}
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 3:33 pm
by Xaos
I forgot to include the part where it says the row numbers must be right next to each other. Smh. Here is my final, and correct,code.
Code: Select all
public boolean scores100(int[] scores) {
for(int i=1; i <= scores.length-1; i++){
if(scores[i] == 100){
if(scores[i-1] == 100){
return true;
}
}
}
return false;
}
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 3:42 pm
by a_bertrand
But that would check only if the number is 100? That's no checking any 2 numbers nearby
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 3:43 pm
by Xaos
a_bertrand wrote:But that would check only if the number is 100? That's no checking any 2 numbers nearby
Well the problem just asked specifically for 100. If I did want to check for any number, I could just do the same thing, but always check if i-1== i
Re: Array/Loop Question
Posted: Fri Mar 14, 2014 3:54 pm
by a_bertrand
Then why didn't you stated it? Sorry but you was by far not clear

Re: Array/Loop Question
Posted: Fri Mar 14, 2014 5:19 pm
by Xaos
a_bertrand wrote:Then why didn't you stated it? Sorry but you was by far not clear

I know
