Please arrays, and loops - java

A. how do i write this simpler?
if (fclass[0] == 0 && fclass[1] == 0 && fclass[2] == 0 && fclass[3] == 0 && fclass[4] == 0 && fclass[5] == 0 && fclass[6] == 0 && fclass[7] == 0 && fclass[8] == 0 && fclass[9] == 0 && fclass[10] == 0){
}else{
}
B. Solved! How would i scan an array (atm all values in it are at 0), when i change some of the element are set to one and show only the ones that have a 0 still.
example:
if fclass[1], fclass[2], fclass[4], fclass[5], fclass[6], fclass[10],
were all set to 1. How would i get my program to show me fclass[3], fclass[7],
fclass[8], and fclass[9]?
Thanks for the help...
for (int f = 0; f <= fclass.length; f++){
if (fclass[f] == 0){
System.out.println(fclass[f]);
}
C. My teacher requires us to learn GUI but doesn't know it herself, any good websites to start learning that?

A. You can set a boolean and loop through them to check if all are zero. I'm assuming that your fclass variable is int[].
boolean flag = true;
for (int i : fclass)
{
flag &= (i == 0);
}
if (flag)
{
// if all are zero...
}
else
{
// if one of them is not zero...
}
B. Similarly you can loop through the array and scan what is not equal to zero.
for (int i : fclass)
{
if (i != 0)
System.out.println(i); // these are array not equals to zero.
}

A.
boolean allZero = true;
for(int i=0; i<fclass.length; i++){
if(fclass[i] !=0) allZero = false;
}
if(allZero){
}
else{
}
B.
for(int i=0; i<fclass.length; i++){
if(fclass[i] ==0) System.out.println(i + "is 0");
}
C. Google

A:
boolean checkFClass(int[] flcass) {
for(int i =0 ; i < 11; i++) {
if(fclass[i] !=0) {
return false;}
}
return true;
}
B:
for(int i = 0 ; i < fclass.lenght ; i++) {
if(fclass[i] != 1) { System.out.println(fclass[i]);}
}

Related

Rat in a Maze using Stack (Java)

We are given a 2D character array and, starting from a given point, we have to find an 'exit', which is a '0' in the perimeter of the given matrix. The program returns true if a path is found, which will print a message when I run it in my main method later. We can only move up, left, down or right to a nearby '0'. I have already tried to make this work, however I get a memory error, which probably means I am stuck in an infinite loop. I have tried to implement this project using a Stack that I made using Nodes, which I also implemented myself using generics, like this: e.g.
StringStackImpl<int[][]> s = new StringStackImpl<>();
in a different .java file. These work fine. I tried to store the coordinates of a character in the matrix like this:
StringStackImpl<int[]> s = new StringStackImpl<>();
s.push(new int[]{i, j});
Here is my code:
private static boolean hasExit(char[][] maze, int n, int m, int i, int j) {
int d = -1;
boolean[][] visited = new boolean[n][m];
for (int a = 0; a < visited.length; a++) {
for (int b = 0; b < (visited[a]).length; b++) {
visited[a][b] = false;
}
}
StringStackImpl<int[]> s = new StringStackImpl<>();
s.push(new int[]{i, j});
while (!(s.isEmpty())) {
int[] temp = s.peek();
d += 1;
i = temp[0];
j = temp[1];
if (((i == 0) || (i == n-1) || (j == 0) || (j == m-1)) && (maze[i][j] == '0')) {
return true;
}
if (d == 0) {
if ((i-1 >= 0) && (maze[i-1][j] == '0') && !(visited[i-1][j])) {
visited[i-1][j] = true;
s.push(new int[]{i-1, j});
d = -1;
}
}
else if (d == 1) {
if ((j-1 >= 0) && (maze[i][j-1] == '0') && !(visited[i][j-1])) {
visited[i][j-1] = true;
s.push(new int[]{i, j-1});
d = -1;
}
}
else if (d == 2) {
if ((i+1 < n) && (maze[i+1][j] == '0') && !(visited[i+1][j])) {
visited[i+1][j] = true;
s.push(new int[]{i+1, j});
d = -1;
}
}
else if (d == 3) {
if ((j+1 < m) && (maze[i][j+1] == '0') && !(visited[i][j+1])) {
visited[i][j+1] = true;
s.push(new int[]{i, j+1});
d = -1;
}
}
else {
s.pop();
d = -1;
}
}
return false;
}
}
EDIT: It works now, thanks to kendavidson! <3
At first glance, and trusting you about StringStackImpl, I think you should only use d = -1;in the last else. Right now you are always setting it back to -1, and so you only check the d == 0 condition. From what I understood, d is the direction possible, and so should go from 0 to 3 ?
Other than that, take some time to give meaningfull names to your variables :
visited[i][j] is true when the node [i][j] has not been visited yet... That's counter-intuitive, and doesn't help others, or yourself, from understanding your code.
Are you forced to use char for i and j ? It really tends to make the code long and tedious for nothing.

Q: Solve almostIncreasingSequence in Java (Codefights)

I can't pass the final hidden test.Could you tell me what I miss?Thanks in advance.
Here are the statements: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
boolean almostIncreasingSequence(int[] sequence)
{
boolean increase = true;
List<Integer> list = new ArrayList<>();
for (int a :sequence )
{
list.add(a);
}
System.out.println(list);
if(list.size()==1)
{
return false;
}
for (int i = 0;i < list.size()-1 ;i++ )
{
if (list.get(1)<=list.get(0))
{
list.remove(0);
break;
}
if(list.get(i+1)<=list.get(i))
{
if (list.get(i+1)>list.get(i-1))
{
list.remove(i);
}
else
{
list.remove(i+1);
}
break;
}
}
for (int i =0;i<list.size()-1 ;i++ )
{
if (list.get(i+1)<list.get(i) || list.get(i+1)==list.get(i) )
{
increase = false;
}
}
return increase;
}
This is the linear solution I came up with. It involves muting the array so you don't have to loop through the array again.
boolean almostIncreasingSequence(int[] sequence) {
int removed = 0;
for (int i = 0; i < sequence.length - 2 && removed <= 2; i ++) {
int a = sequence[i];
int b = sequence[i+1];
int c = sequence[i+2];
if (a >= b) {
removed++;
sequence[i] = b -1;
}
if (b >= c){
removed++;
if (a == c) {
sequence[i+2] = b +1;
} else {
sequence[i+1] = a;
}
}
}
return removed <= 1;
}
Here's my solution with O(n) complexity
`
boolean almostIncreasingSequence(int[] sequence) {
int flag = 0;
int i = 0;
while(i<sequence.length-1){
if(sequence[i] < sequence[i+1]){
i = i+1;
continue;
} else {
flag = flag + 1;
if(i>0 && i+2 < sequence.length && sequence[i+1] <= sequence[i-1] && sequence[i+2] <= sequence[i]){
flag = flag + 1;
} else {
i = i+1;
}
if(flag > 1){
return false;
}
}
}
return true;
}
`
This worked for me
boolean almostIncreasingSequence(int[] sequence) {
int failed = 0;
boolean one_chance;
for(int i = 0; i < sequence.length - 1; i++){
int curr=i,next=i+1;
if(sequence[curr] >= sequence[next]) {
failed++;
if( curr > 0 && next < sequence.length - 1 ){
// Problem is not on head neither tail
// So check if removing one of 2 problematic numbers solves the issue
one_chance = false;
if( sequence[curr - 1] < sequence[next] )
one_chance = true ;
if ( sequence[curr] < sequence[next+1] )
one_chance = true ;
if( one_chance == false ) return false;
}
}
if( failed > 1 ) return false;
}
return true;
}
Spoiler Alert!
I could not pass the last hidden test either. So I spent 10,000 of my 12,300 coins (ouch!) to unlock them.
It turns out, the last test (#34) is expecting an outcome of true, and is passing an array of ints 100,000 long, in order from 1 to 100000! (So big that the only way I could see this was to do this in my code:
System.out.printf("length: %d%nlastValue:%d%n",
sequence.length, sequence[sequence.length - 1]);
I'm not sure why my code didn't pass, but I did at least unlock that hidden test, so now you can know what it is without having to spend coins to unlock it yourself.
I then got lazy and added this line at the top of my method to make it pass:
if (sequence.length == 100000
&& sequence[sequence.length - 1] == 100000) {
return true;
}
Here is a solution that works by using recursion to check the remainder of the array.
The issue is when the code hits a number that doesn't belong it can't be sure which of the two numbers is the offender so I just check the array starting from where the problem was detected and skipping the "bad" numbers. If it fails again while skipping a number it's game over.
This is in JavaScript, but it can easily be translated.
function almostIncreasingSequence(sequence) {
if(!sequence || sequence.length < 3) return true;
return checkSorted(sequence);
}
function checkSorted(arr, start = 0, skip) {
let last = arr[start === skip ? skip + 1 : start];
for(let i = start + 1; i < arr.length; i++) {
if(skip === i) continue;
let current = arr[i];
let lastIndex = skip === i - 1 ? i - 2 : i - 1;
let last = arr[lastIndex];
if(current <= last) {
if(skip !== undefined) return false;
return checkSorted(arr, i - 1, i) || checkSorted(arr, i - 1, i - 1);
}
}
return true;
}
def almostIncreasingSequence(sequence):
initial_length = len(sequence)-1
length = len(sequence)-1
count = 0
i = 0
while i < length:
if sequence[i] >= sequence[i+1]:
if i == 0:
sequence.pop(0)
count +=1
length = len(sequence)-1
i =0
elif sequence[i] == sequence[i+1]:
sequence.pop(i+1)
length = len(sequence)-1
i -= 1
count += 1
elif sequence[i] > sequence[i+1]:
if count ==0 and i + 1 == length:
return True
else:
if max(sequence) == sequence[i] and count == 0:
sequence.pop(i)
length = len(sequence)-1
i -= 1
count += 1
else:
sequence.pop(i+1)
length = len(sequence)-1
i -= 1
count +=1
else:
i += 1
length = len(sequence)-1
if count == 1:
if initial_length - length == 1:
return True
else:
return False
elif count > 1:
if initial_length - length > 1:
return False
else:
return True
boolean almostIncreasingSequence(int[] sequence) {
int count = 0;
int size = sequence.length;
if(size==1)
return true;
for(int i=0;i<size-1 && count<=1;i++){
if(sequence[i]>=sequence[i+1]) {
count++;
if(i>0 && (i+2)<size && sequence[i-1]>=sequence[i+1] && sequence[i]>=sequence[i+2]) {
count++;
}
}
}
return (count<=1);
}
boolean solution(int[] sequence) {
boolean increasing = true;
boolean isany = false;
for(int i=0;i<sequence.length;i++){
ArrayList<Integer> sequenceArrayList = new ArrayList();
for(int a : sequence){
sequenceArrayList.add(a);
}
sequenceArrayList.remove(i);
for(int j=0;j<sequence.length-2;j++){
if(sequenceArrayList.get(j)>=sequenceArrayList.get(j+1)){
increasing = false;
break;
}else{
increasing = true;
}
}
if(increasing){
isany = true;
}
}
return isany;
}

Search and mark in two-dimensional Java-Array

I have an two-dimensional Array in Java. The values are like:
2 1 0 2 1
1 0 2 2 2
1 1 1 2 2
0 0 0 2 2
I want to change now all "2"s to a 1, but only the ones who are bordering the other ones. So after saying "Change (4|4) to "2", I want to have my Array like this:
2 1 0 1 1
1 0 1 1 1
1 1 1 1 1
0 0 0 1 1
What is the fastest way of doing this?
Assuming your working with a two dimensional array:
have int x and y set to 0
start from [x][y] on the array
Step 1: Check to if number equals "2"
If it does and:
0<x<4 and 0<y<4: Check [x-1][y-1],[x][y-1],[x][y+1],[x-1][y],[x+1][y], and [x+1][y+1]
x=0 and 0<y<3: Check [x][y-1],[x][y+1],[x+1][y], and [x+1][y+1]
x=4 and 0<y<3: Check [x-1][y-1],[x][y-1],[x][y+1],[x-1][y]
0<x<4 and y=0: Check [x][y+1],[x-1][y],[x+1][y], and [x+1][y+1]
0<x<4 and y=3: Check [x-1][y-1],[x][y-1],[x-1][y],[x+1][y]
and so on....
check to see if [x][y] = any of the checks
if so: store a 1 in [x][y] in an alternative array of the same size (lets call it flags)
iterate and repeat from step 1 until you have gone through the entire array
run through the flags and if the value is 1 at any address [x][y] change the corresponding value in our original array to "1".
sorry its a bit wordy and maybe confusing, please let me know if I need to clarify
Where is your code of what you've tried so far?
You could try using a nested for loop, then put if-else statements in the inner loop that
1. Will look at the values to the left and right of the index
2. If it is next to a 2 (and is a 2), will swap/assign the 2 in the index w/ a 1, otherwise it will just leave it alone.
Are you looking to make this scalable so that it would work with any array of 0s, 1s and 2s or just this exact array that you provided?
Please let me know if you need any clarification and include your code so that we can have something to work off of.
This example uses 2D array as array of arrays.
It generates 2D array with random numbers:
array[][] is the source array and all replacement routine will be performed in replaced[][] array (which is a copy of source one).
SIZE_I - number of rows and SIZE_J - number of columns;
RANGE_FROM - minimum number in array and RANGE_TO - maximum number;
SEARCH - number to search;
REPLACE - number to replace.
quantity - number or found and replaced items.
It prints source array to screen;
It checks source array for matching SEARCH constant with array item array[i][j]. Depending on item's location, several conditions should be met to replace this item in replaced[][] array and to increase quantity variable by one.
It prints replaced array to screen and number of replaced items.
I believe you can gain performance by using 2D array as one array.
For example your 2D array may be represented as {2,1,0,2,1,1,0,2,2,2,1,1,1,2,2,0,0,0,2,2} but you should handle it properly.
public static void main(String[] args) {
final int RANGE_FROM = 0;
final int RANGE_TO = 2;
final int SEARCH = 2;
final int REPLACE_TO = 1;
final int SIZE_I = 4;
final int SIZE_J = 5;
int quantity = 0;
int array[][] = new int[SIZE_I][SIZE_J];
int replaced[][] = new int[SIZE_I][SIZE_J];
// Generate arrays
for (int i = 0; i < SIZE_I; i++) {
for (int j = 0; j < SIZE_J; j++) {
array[i][j] = (int) (RANGE_FROM + Math.random() * (RANGE_TO - RANGE_FROM + 1));
replaced[i][j] = array[i][j];
}
}
// Display array
System.out.println("Source array:");
for (int x[]: array) {
for (int y: x) {
System.out.print(y + " ");
}
System.out.println();
}
System.out.println();
// Check array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (i == 0 && j == 0) {
if (array[i][j] == SEARCH && (array[i+1][j] == SEARCH || array[i][j+1] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i == 0 && j == array[i].length - 1) {
if (array[i][j] == SEARCH && (array[i+1][j] == SEARCH || array[i][j-1] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i == array.length -1 && j == 0) {
if (array[i][j] == SEARCH && (array[i-1][j] == SEARCH || array[i][j+1] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i == array.length -1 && j == array[i].length - 1) {
if (array[i][j] == SEARCH && (array[i][j-1] == SEARCH || array[i-1][j] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i == 0 && j != 0 && j != array[i].length - 1) {
if (array[i][j] == SEARCH && (array[i][j-1] == SEARCH || array[i+1][j] == SEARCH || array[i][j+1] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i != 0 && i != array.length - 1 && j == array[i].length - 1) {
if (array[i][j] == SEARCH && (array[i][j-1] == SEARCH || array[i-1][j] == SEARCH || array[i+1][j] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i == array.length - 1 && j != 0 && j != array[i].length - 1) {
if (array[i][j] == SEARCH && (array[i][j-1] == SEARCH || array[i-1][j] == SEARCH || array[i][j+1] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else if (i != 0 && i != array.length - 1 && j == 0) {
if (array[i][j] == SEARCH && (array[i-1][j] == SEARCH || array[i][j+1] == SEARCH || array[i+1][j] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
else {
if (array[i][j] == SEARCH && (array[i-1][j] == SEARCH || array[i][j+1] == SEARCH || array[i+1][j] == SEARCH || array[i][j-1] == SEARCH)) {
quantity++;
replaced[i][j] = REPLACE_TO;
}
}
}
}
// Display replaced array
System.out.println("Replaced array:");
for (int x[]: replaced) {
for (int y: x) {
System.out.print(y + " ");
}
System.out.println();
}
System.out.println();
System.out.println("Replace quantity: " + quantity);
System.out.println();
}

Solution of twoTwo riddle on codingBat in Java

The question is about Solving this problem from codingBat in Java.
Problem Statement:
Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo({4, 2, 2, 3}) → true
twoTwo({2, 2, 4}) → true
twoTwo({2, 2, 4, 2}) → false
First of all going by the problem statement that every 2 that appears in the array is next to another 2. then
do you think as suggested the outcome for the first inputs shown above
should be true?
twoTwo({4, 2, 2, 3}) → true
Because as I see it it the first 2 itself that appears in the array is next to 4 not 2
am I confused or it's a wrongly stated question? I had to grapple with the problem to somehow get the right code to crack the problem as below but it seems a hotch potch:
public boolean twoTwo(int[] nums) {
if(nums.length==0)
{
return true;
}
if(nums.length==1)
{
return !(nums[0]==2);
}
if((nums.length==2))
{
if((nums[1]==2)&&(nums[0]==2))
return true;
else
return false;
}
for(int i=0;i+2<nums.length;i++)
{
if((nums[i]!=2)&&(nums[i+1]==2)&&(nums[i+2]!=2))
return false;
}
if((nums[nums.length-2]!=2)&&(nums[nums.length-1]==2))
return false;
return true;
}
Any efficient alternate solutions are welcome.
Thanks!
Here's how I would do it. It's a bit easier to follow I think:
public boolean twoTwo(int[] nums)
{
for (int i=0; i<nums.length; i++)
{
if (nums[i] != 2)
continue;
if (i >= 1 && nums[i-1] == 2)
continue;
if (i < (nums.length-1) && nums[i+1] == 2)
continue;
return false;
}
return true;
}
The solution I got to the problem is below:
public boolean twoTwo(int[] nums) {
final int length = nums.length;
for (int i = 0; i < length;){
int count = 0; // Used to count following 2's
while(i < length && nums[i++] == 2){
count++;
}
if(count == 1){ // No adjacent 2's! Set doesn't work.
return false;
}
}
return true; // Didn't come across a lone 2
}
The way that I handle this, is that I count all the adjacent 2's. If the count is not 1, we are good. This means that there was either no 2 at that index, or a group of 2's was present. This holds, since we traverse the array in a single direction.
A good thing about this solution is that it will work for an array of any size. Note that it would have a linear complexity, even though 2 loops are present. They both just traverse using the same index value, only ever sweeping over the array once.
If at any time we find a 2, then check the following only to find there are 0 following 2's (denoted by count), we return false.
public boolean twoTwo(int[] nums) {
for (int i=0; i<nums.length; i++) {
if(nums[i] == 2) { //If current number is 2
if (
// if prev or next is not 2 return true
!(i-1>=0 && nums[i-1] == 2) &&
!(i+1<nums.length && nums[i+1] == 2)
) { return false; }
}
}
return true;
}
For the sake of simplicity and clean code, this code forces the check
i-1>=0 and i+1<nums.length in every iteration.
This can be avoided by iterating from (1...nums.length-1) and checking the edge cases separately.
I know this is an old question, but I came up with a new solution. Short, and with no complicated conditionals.
public boolean twoTwo(int[] nums) {
int position = -2;
boolean result = true;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 2) {
result = position == i - 1;
position = i;
}
}
return result;
}
Next to means either before or after. Loop through each number and check the values before and after to see if there's an adjacent 2. The special cases are when you're checking the 1st and last element because there won't be an element before or after to check.
public boolean twoTwo(int[] nums) {
if(nums.length == 1 && nums[0] == 2)
return false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 2) {
if(i == 0) { // check the next element
if(nums[i+1] != 2)
return false;
}
else if(i == (nums.length - 1)) { // check the previous element
if(nums[i-1] != 2)
return false;
}
else { // check both
if(nums[i+1] != 2 && nums[i-1] != 2)
return false;
}
}
}
return true;
}
Here is mine solution to two two's problem. I think my solution is clear i.e. understandable.
package codingbat.array2;
public class TwoTwo
{
public static void main(String[] args)
{
}
public boolean twoTwo(int[] nums)
{
boolean twoTwo = true;
for (int i = 0; i < nums.length; i++)
{
if (2 == nums[i])
{
if (i > 0 && 2 == nums[i - 1]
|| nums.length > i+1 && 2 == nums[i+1])
{
twoTwo = true;
i++;
}
else
{
twoTwo = false;
break;
}
}
}
return twoTwo;
}
}
public boolean twoTwo(int[] nums) {
for(int i = 0 ; i < nums.length; i++ ) {
int count = 0;
if(nums[i] == 2 ) {
while(i+1 < nums.length && nums[i+1] == 2 ) {
count ++;
i++;
}
if (count == 0 ) {
return false;
}
}
}
return true;
}
public boolean twoTwo(int[] nums) {
for(int i = 0;i<nums.length;i++)
if(nums[i]==2 && !isTwoBeforeOrAfter(nums,i))
return false;
return true;
}
private boolean isTwoBeforeOrAfter(int[] nums,int i){
return i+1<nums.length && nums[i+1]==2 || i-1>=0 && nums[i-1]==2;
}
public boolean twoTwo(int[] nums) {
float two = 0;
double count = 0;
for (int i = 0; i < nums.length; i++) {
if (i < nums.length - 2 && nums[i] == 2 && nums[i + 1] == 2 && nums[i + 2] == 2) {
return true;
}
if (i < nums.length - 1 && nums[i] == 2 && nums[i + 1] == 2) {
count++; //count the pair
}
if (nums[i] == 2) {
two++;
}
}
return ((count * 2) == two);
//each pair contain 2 ,two"s .so pair*2=total two counts
//count
}
public boolean twoTwo(int[] nums) {
boolean two = false;
boolean result = true;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 2) {
if (two) {
result = true;
} else {
result = false;
}
two = true;
} else {
two = false;
}
}
return result;
}
Here's my solution. Enjoy.
public boolean twoTwo(int[] nums)
{
//If the length is 2 or more
if (nums.length >= 2)
{
//If the last char is a 2, but the one before it is not a char, we return false;
if (nums[nums.length - 1] == 2 && nums[nums.length - 2] != 2)
{
return false;
}
//If larger than three, we create a for loop to test if we have any 2s that are alone.
if (nums.length >= 3)
{
for (int i = 1; i < nums.length-1; i++)
{
//If we find a two that is alone, we return false;
if ((nums[i] == 2) && (nums[i-1] != 2 && nums[i+1] != 2))
{
return false;
}
}
}
//If we don't return false, we return true;
return true;
}
//If we have less than two characters, we return true if the length is 0, or \
//One the one number there is not a 2.
else
{
return ((nums.length == 0) || !(nums[0] == 2));
}
}
public boolean twoTwo(int[] nums) {
int len = nums.length;
Boolean check = false;
int count = 0;
for(int i=0; i<len ; i++){
if(nums[i]==2){
count++;
if((i<len-1 && nums[i+1]==2) || (i>0 && nums[i-1]==2)) check = true;
else check = false;
}
}
if(count==0) check = true;
return check;
}
public boolean twoTwo(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] == 2) count++;
else if (count == 1) return false;
else count = 0;
return count != 1;
}
Every time we encounter a 2, we increase the counter of consecutive 2s.
When it's not a 2 — but the counter indicates that there was a single 2 before it —, we know we've found a lonely 2.
Otherwise the search continues, resetting the 2-counter.
easy to understand)
static boolean twoTwo(int[] nums) {
int len = nums.length;
boolean result = true;
boolean found = false;
for(int i=0; i<len; i++){
//if it not 2, no meaning to go true other if-s
if(nums[i] !=2) {found = false; continue;}
// if current element is 2 and found is true(last element is 2)
if(nums[i] ==2 && found) result = true;
// if current element is 2, but last element not
if(nums[i] ==2 && !found){
found = true;
result = false;
}
}
return result;
}
This might be easier to follow if the other suggestions confuse you..
public boolean twoTwo(int[] nums) {
int len = nums.length;
if(len == 0) return true; // no 2's to worry about
if(len == 1) return nums[0] != 2; // make sure it's not a single 2
for(int i = 1; i < len -1; i++){ // loop for each except edge cases
if(nums[i] == 2 && nums[i-1] != 2 && nums[i+1] != 2) return false; // check surrounding
}
if(nums[len - 1] == 2) return nums[len - 2] == 2; //if last num is 2 check for 2 before it
return true; // made it here it's true
}
that one was tough for me... here's mine:
public boolean twoTwo(int[] nums) {
boolean two = false, res = true;
for (int i : nums) {
if (i == 2) {
if (two)
res = true;
else {
two = true;
res = false;
}
} else {
two = false;
}
}
return res;
}
One more alternative. Here is the main idea:
Convert array into String. Add a character different from "2" at the beginning and end of the string, to avoid going out of bounds.
Look for standalone "2" - if element of the string is equal to 2, check whether chars immediately before and after are also equal to "2". If they are it means that not all "2" are adjacent, and therefore method returns false.
public boolean twoTwo(int[] nums) {
// convert array to string
String text = "";
for (int i = 0; i < nums.length; i++) {
text += String.valueOf(nums[i]);
}
text = " " + text + " ";
// find standalone "2"
for (int i = 1; i < text.length() - 1; i++) {
if (text.charAt(i) == '2' && text.charAt(i - 1) != '2' && text.charAt(i + 1)
!= '2') {
return false;
}
}
return true;
}

Java: Array Index Out of Bound Exception

When I compiled I got here error java.lang.ArrayIndexOutOfBoundsException: -1. I checked code 3 times and no error found there, also I am not writing after end of array.
Random nahoda = new Random(); int[][] minPol = new int[5][5];
int[][] cisPol = new int[5][5];
for(int i = 0;i<5;i++)
{
for(int j=0;j<5;j++)
{
minPol[i][j] = nahoda.nextInt(2);
cisPol[i][j] = 0;
}
}
for(int i = 0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(minPol[i][j]!=0)
{
if(i != 0 || j != 0 || i != 4 || j != 4)
{
cisPol[i+1][j+1]++;
cisPol[i+1][j-1]++;
cisPol[i-1][j+1]++;
cisPol[i-1][j-1]++;
cisPol[i+1][j]++;
cisPol[i-1][j]++;
cisPol[i][j+1]++;
cisPol[i][j-1]++;
}
else
{
if(i == 0)
{
if(j == 0)
{
cisPol[i+1][j+1]++;
cisPol[i][j+1]++;
cisPol[i+1][j]++;
}
else if(j == 4)
{
cisPol[i+1][j]++;
cisPol[i+1][j-1]++;
cisPol[i][j-1]++;
}
else
{
cisPol[i+1][j+1]++;
cisPol[i][j+1]++;
cisPol[i+1][j]++;
cisPol[i+1][j-1]++;
cisPol[i][j-1]++;
}
}
else if(i == 4)
{
if(j == 0)
{
cisPol[i-1][j+1]++;
cisPol[i-1][j]++;
cisPol[i][j+1]++;
}
else if(j == 4)
{
cisPol[i-1][j-1]++;
cisPol[i-1][j]++;
cisPol[i][j-1]++;
}
else
{
cisPol[i][j-1]++;
cisPol[i][j+1]++;
cisPol[i-1][j+1]++;
cisPol[i-1][j]++;
cisPol[i-1][j-1]++;
}
}
}
}
}
}
I am beginner in Java and thanks for tips
Look at this condition:
if(i != 0 || j != 0 || i != 4 || j != 4)
That doesn't do what you want it to. It will always be true, because i can't be simultaneously equal to 0 and 4.
Therefore you'll end up going into here when j is 0:
cisPol[i+1][j-1]++;
Bang.
Try this;
Replace this line;
if(i != 0 || j != 0 || i != 4 || j != 4)
with
if( i>=1 && j>=1 && j<4 && i<4)
That will make sure you don't reference from your array with a negative index or a value greater than 4.

Categories

Resources