how to compare int and array? - arrays

Im a programming student, I need help with comparing int and array.
idNumber =Integer.parseInt(JOptionPane.showInputDialog("Enter ID number:"));
for (i = 0; (i < student.length) && (idNumber == student[i]); i++) {
choiceIsGood = true;
I have declared:
int idNumber;
final int[] student = { 2064009, 2062895, 2063427 };
I want to validate the entry if it is registered in my array.
how will I compare this and proceed with boolean = true;

1. idNumber =Integer.parseInt(JOptionPane.showInputDialog("Enter ID number:"));
2. bool choiceIsGood = false;
3. for (i = 0; (i < student.length); i++)
4. {
5. if(idNumber == student[i]) // student[i] is an int, idNumber too !
6. { // if idNumber == 2064009 or 2062895 or 2063427
7. choiceIsGood = true; // no need to continue to loop over your array
8. }
9. }
10.if(choiceIsGood)
11.{
12. // Do some stuff
13.}
Few explanations:
Line: 1. Get User input
Line 2. Declare var outside of the validation system
Line 3. Go through every items of your array
Line 5. check if the user input is the current element of the array
Line 7. Assign true to choiceIsGood
Line 10. Check if we passed on choiceIsGood = true line.
You never compare two objects which are not of the same type; but the content of an array which has the same type as your input.

Related

How do I get the integer method "guess" to go into another method as an array?

else {
masterNum[3] = guess % 10; //checks integers in their respective positions
masterNum[2] = ((guess - guess%10)/10)%10;
masterNum[1] = ((guess - guess % 100)/100)%10;
masterNum[0] = (guess - guess % 1000)/1000;
masterDigit(guess, masterNum);
}
//}
//This method determines the total number of correct digits but not
//necessarily in the correct position
public static int masterDigit (int [] guess,int [] code) //int [] guess
{
int i,j,k,number;
int [] tempGuess = new int [4]; //an array to hold a copy of a code
boolean found;
number = 0;
for(k=0; k<4; k++) //copies code to tempGuess so code
//doesn't get changed (you can't just assign code to tempGuess)
tempGuess[k] = code[k];
for(i = 0; i < 4; i++)
{
j=0;
found = false;
while(j < 4 && found == false) // a while loop instead of a
// for loop so duplicates are only counted once
{
if(guess[i] == tempGuess[j])
{
found = true;
tempGuess[j] = -1; // fills up tempGuess with an impossible
// value so that index only gets
// counted once
number++;
}
j++;
}
}
return number;
}
This code is for a Mastermind game with integers. Upon running through the compiler, there is an error saying that integer "guess" cannot be converted to an array. How can I get my guess (defined as an integer scanner console) to go into this method that will check which numbers are correct?

Algorithm to step over array elements as per the given condition

I am practicing to solve this problem, and have gotten 5 test cases passed but some test cases are failing I am not able to figure out what's the issue in my algorithm. Although I tried with some test data from failed test cases, most of them are coming correctly but I believe some are incorrect hence leading to my algorithm failure. So If someone can give an insight on the correct way to implement this algorithm that would be very helpful or where am I going wrong in my implementation.
My Algo:
1. Index for the move is at index '0' of string (say moving index)
2. Loop over the string starting with index '1' of string:
2.1. check if (moving index + leap) can outrun the array:
2.2. If not then, check whether the character is 1 or 0 :
2.2.1 Check for the number of '1's that are continuous, if they exceed the leap value then return false (as anyway we will not be able to jump).
2.2.2 If its 0, then check whether its a zero after continuous '1's.
If not so, continue moving forward one step at a time.
If so, first try to skip over those continuous '1's by checking whether (moving index + leap) is allowed or not as per the rule.
If not allowed, check in a while loop till what point we can move backwards one step at a time to get (moving index + leap) to satisfy.
If not possible, return false.
I don't know whether this is an efficient way to implement solution of this sort of problem, any other possible methods are much appreciated.
code:
import java.util.*;
public class Solution {
public static int leapStep(int index,int leap,int len,int[] game){
if(game[index+leap]==0){
index += leap;
}
return index;
}
public static boolean canWin(int leap, int[] game) {
int index = 0;
int len = game.length;
int consecutiveLength=0;
for(int i=1;i<len;){
if(index+leap>len-1){
return true;
}
if(game[i]==1){
consecutiveLength++;
if(consecutiveLength>=leap){
return false;
}
i++;
}else{
if(consecutiveLength==0){
index =i;
i++;
}else{
if(index+leap<=len-1){
int tryLeap = leapStep(index,leap,len,game);
if(index < tryLeap){
index = tryLeap;
tryLeap =0;
i = index+1;
}else if(index>0 && game[index-1]==0 ){
boolean notViable = false;
while(index>0){
if(game[index-1]!=0)
return false;
index -= 1;
i = index+1;
tryLeap = leapStep(index,leap,len,game);
if(index<tryLeap){
index = tryLeap;
i = index+1;
tryLeap=0;
notViable = false;
break;
}
else{
notViable = true;
}
}
if(notViable){
return false;
}
}else{
return false;
}
}
consecutiveLength=0;
}
}
}//closing for
return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int q = scan.nextInt();
while (q-- > 0) {
int n = scan.nextInt();
int leap = scan.nextInt();
int[] game = new int[n];
for (int i = 0; i < n; i++) {
game[i] = scan.nextInt();
}
System.out.println( (canWin(leap, game)) ? "YES" : "NO" );
}
scan.close();
}
}
To me, a better approach is to solve this recursively as below (it passed all the tests):
public static boolean canWin(int[] array, int index, int leap) {
// the only case when we lose
if (index < 0 || array[index] > 0) {
return false;
}
// if you're standing in the last entry or (index + leap) >= array.length then win
if ((index >= array.length - 1) || ((index + leap) >= array.length)) {
return true;
}
// mark it as visited so that not to iterate over it again
array[index] = 1;
// check all 3 conditions then recursively again
return canWin(array, index + 1, leap) || canWin(array, index - 1, leap) || canWin(array, index + leap, leap);
}
In the input below several pairs of lines are shown. The first element of each pair stands for leap and the second one for an array.
Input:
3
0 0 0 0 0
5
0 0 0 1 1 1
3
0 0 1 1 1 0
1
0 1 0
Output:
true
true
false
false
Explanation:
Let's say your current position is index.
If it's negative or the array value is larger than 0 then the game is lost. If it's the last position or index + leap reaches at least the length of the array then the game is won by definition.
Otherwise, the only possible moves from here could be index - 1 or index + 1 or index + leap. So, you repeat step 1 for each of the latter indices and take OR of the result because finding a single path is enough. Don't forget to set a value of the cell to 1 because it doesn't make sense to visit it the second time - we don't want to repeat the same moves over and over again and crash.
Your pseudo-code seems fine, but there a few mistake in your code, that may be the cause of your trouble.
The least problematic first, if(index+leap<=len-1) inside your loop is useless, you can remove it without modify the behaviour of your algorithm. It is the case because you already checked it in the first line of the loop and entered an else keyword.
This one is about your variables index and i. Their meaning isn't clear to me after a few complete read, and they look like the same. It might cause you trouble because you use the variable index inside your call to leapStep, but index is often one step behind i. It's confusing.
I did not found an example where your code fails.
Here is my solution HackerRank accepted. It is an iterative one, close to yours. Its principle is simple: starting from position 0, as we increase step by step our position, keep track of the positions you have access to (in variable memoTab, I removed the dp name as it can be frightening): if we are on a position we already reached before, then we can go to +1 or +leap.
It would be enough if it wasn't allowed to backtrack and go the reverse direction. To deal with that, whenever we reach some 1s, I keep in memory the next 0. And if I encounter a position I can reach just after, I go back to that 0 and say I can go there.
Here is the code, first a little helper function that returns true if the game is finished. Given a game and an index it says if we can go to that index and write it to the memo.
public static boolean check(int[] game, boolean[] memo, int index){
if(index >= 0 && index < game.length){
if(game[index] != 1){
memo[index] = true;
}
}
return index >= game.length;
}
This is the solver function, it first reads the values, then starts looping.
public static void solveOne(){
int n = sc.nextInt();
int leap = sc.nextInt();
int[] game = new int[n];
for (int i = 0; i < n; i++) {
game[i] = sc.nextInt();
}
int index = 0;
boolean[] memoTab = new boolean[n];
for (int i = 0; i < n; i++) {
memoTab[i] = false;
}
memoTab[0] = true;
boolean rememberIndex0 = false;
boolean gotoIndex0 = false;
int index0 = 0;
boolean finished = false;
We are done with the initialization, let's loop:
while(index < game.length){
// we encounter the first 0 after some 1, keep it in memory !
if(rememberIndex0 && game[index] == 0){
index0 = index;
gotoIndex0 = true;
rememberIndex0 = false;
}
// this index is an index we reached before, we can continue from here
if(memoTab[index]){
// we previously said we need to go back to a lower position
if(gotoIndex0){
gotoIndex0 = false;
index = index0;
memoTab[index] = true;
continue;
}
// it's finished if either is true
finished = check(game, memoTab, index + 1)
|| check(game, memoTab, index + leap);
if(finished) break;
}
// if this position is a 1, then we will keep in memory the next 0
if(game[index] == 1){
rememberIndex0= true;
}
// don't forget incrementing
index += 1;
}
System.out.println(finished?"YES":"NO");
}

What are the methods to trace an array to the following criteria?

The array:
var numberArray:Array= new Array(34,53,2,3,34,26,26,85,3,4,98,2,12);
How do I trace it so the output-panel will show every other item: "34,2,34,26,3,98,12"
How do I trace the numbers that have a lower value than 10
How do I trace the even numbers in the array?
For the reference and general education: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html#map()
// You can init Arrays with [] operator.
var numberArray:Array = [34,53,2,3,34,26,26,85,3,4,98,2,12];
trace(filter(numberArray, evenIndices));
trace(filter(numberArray, belowTen));
trace(filter(numberArray, evenValues));
// In AS3 you can pass method references as function arguments.
// That allows to compose a filtering method, just like Vector.map(...)
// This method will filter the original array
// by the given criteria and return the filtered result.
// Criteria method must accept 2 arguments: element index and value.
function filter(source:Array, criteria:Function):Array
{
var result:Array = new Array;
for (var i:int = 0; i < source.length; i++)
if (criteria(i, source[i]))
result.push(source[i]);
return result;
}
// Returns true if index is an even number.
function evenIndices(index:int, value:int):Boolean
{
return index % 2 == 0;
}
// Returns true if value is less than 10.
function belowTen(index:int, value:int):Boolean
{
return value < 10;
}
// Returns true if value is an even number.
function evenValues(index:int, value:int):Boolean
{
return value % 2 == 0;
}
var numberArray:Array = [34, 53, 2, 3, 34, 26, 26, 85];
1.How do I trace it so the output-panel will show every-other item: "34,2,34,26,3,98,12"
getEventIndexiesOfArray(numberArray);
2.How do I trace the numbers that have a lower value than 10
lenghtLessthanTen(numberArray);
3.How do I trace the even numbers in the array?
checkArrayHasEventLenght(numberArray);
1. getEventIndexiesOfArray() method for get event indexies elements from array.
private function getEventIndexiesOfArray(source:Array):void
{
var resultArr:Array = [];
for (var i:int = 0; i < source.length; i++)
{
if (i % 2 == 0)
resultArr.push(source[i]);
}
trace("Even Indexies Array : " + resultArr.toString());
}
2. lenghtLessthanTen() method for check that array lenght is lessthan 10 or not.
private function lenghtLessthanTen(source:Array):void
{
if (source.length < 10)
trace("Array containt lessthan Ten elements");
}
3. checkArrayHasEventLenght() method check that array containt even lenght or not.
private function checkArrayHasEventLenght(source:Array):void
{
if (source.length % 2 == 0)
trace("Array has even number of elenter code hereements");
}

Loop Iteration Efficient

You have a loop that iterates over 1,000 items. You want to add a newline to every four items. The items are in an array structure that have numeric index starting at 0. How do you do it?
FWIW:
for (int i = 0; i < list.size(); ++i) {
// you want to 'do it' with list[i] here
if (0 == (i+1)%4))
{
// 'you want to add a new line' here
}
}
Just in case what you are really trying to ask is "How do I print these items, four to a line?" here's one way
int nOnLine = 0;
for (i = 0; i < 1000; i++){
// print item i
nOnLine++;
if (nOnLine >= 4){
// print newline
nOnLine = 0;
}
}
if (nOnLine > 0){
// print newline
nOnLine = 0;
}
for (int i = 0; i < list.size(); i += 4) {
// add to the item
}
The above iterates over every fourth item instead of every single item.
for(i=3;i<len;i=i+4) { // where len is the length of your array
ary[i]+='\n'; // use string append operator of your language.
}
which will add a newline to every fourth item, i.e. items 3, 7, 11, etc.
EDIT
Changed to fulfill the OP's criteria.

Can anyone decypher why this 'find unique values' process doesn't work as intended?

The goal is that for a variable that is an array of:
typedef struct {
GLuint vertex;
GLuint normal;
} indice_pairs_t;
, we want to find all the pairs that are unique and put them in an appropriate order of appearance with unique pair indices intact.
For example: if initial pairs are
2 3
6 7
6 7
4 5
(the 2nd and 3rd pairs are same)
then the final order will be
0 1 1 2
('2 3' was 0, first '6 7' was 1 but also the second '6 7'; '4 5' was 2 and so on)
The following code attempts to do that but final order appears to be always '0 1 2 3 4 5' and so on. If 'break;' is removed, it becomes a mess; too many increments.
// First is always unique and first in order:
unique[0] = pairs[0];
order[0] = 0;
num_unique = 1;
// Skip first, we just did it:
for (i = 1; i < num_pairs; i++) {
// Check if what we have is already the same
for (y = 0; y < num_unique; y++) {
if (unique[y].vertex == pairs[i].vertex&&unique[y].normal == pairs[i].normal) {
/* A new pair was found to be the same; put the old unique index in order;
keep num of unique items same: */
order[i] = y;
} else {
/* A new pair was unique; copy it in unique pairs and increment number
of unique items; put in order the new number */
unique[num_unique] = pairs[i];
order[i] = num_unique;
num_unique++; // it follows since it was already incremented to 1.
break;
}
}
}
It's a pretty inefficient algorithm. The complexity is O(n2). You could do better, by using a sorted sequence.
What you have is obviously buggy, but the idea seems clear. For every new value (next i) it is checked, if that value is already among unique values stored so far. That's what the inner loop is for. If the match is found, order[i] = y and the next i should be checked, so you can break. If the match is not found for current y however, you need to check next y. Only after all y were checked, you know the value is unique, so the part in the else clause should be moved outside the inner loop. I think the fixed version should look like this:
unique[0] = pairs[0];
order[0] = 0;
num_unique = 1;
// Skip first, we just did it:
for (i = 1; i < num_pairs; i++) {
// Check if what we have is already the same
for (y = 0; y < num_unique; y++) {
if (unique[y].vertex == pairs[i].vertex && unique[y].normal == pairs[i].normal) {
/* A new pair was found to be the same; put the old unique index in order;
keep num of unique items same: */
order[i] = y;
break;
}
}
if(y == num_unique){
/* No match was found in the inner loop,
so y reached num_unique. You could use a flag
to indicate this, which might be more readable*/
/* A new pair was unique; copy it in unique pairs and increment number
of unique items; put in order the new number */
unique[num_unique] = pairs[i];
order[i] = num_unique;
num_unique++; // it follows since it was already incremented to 1 in the beginning.
}
}

Resources