Check if numbers are successive - java

for(int i = 0; i < aLenght; i++) {
for(int j = 0; j < bLenght; j++) {
if(aChars[i] == bChars[j]) {
System.out.println(j +" == "+ i);
}
}
}
For instance the code above generates the following output:
3 == 0
5 == 0
4 == 1
6 == 1
Now I would like to check whether there exist successive numbers on both sides. For instance the example above would return true, because 3 == 0 and 4 == 1 are successive.

try this
for(int i = 0; i < aLenght - 1; i++) {
for(int j = 0; j < bLenght - 1; j++) {
if(aChars[i] == bChars[j] && aChars[i + 1] == bChars[j + 1]) {
return true;
}
}
}
notice that this covers the length of the array even when it iterates to ALenght - 1. Because when it reaches aLenght - 2, it will be compared with aLenght - 1 as well in
(aChars[i] == bChars[j] && aChars[i + 1] == bChars[j + 1]).
You can check it running this:
#Test
public void successive() {
char[] a = new char[]{'a', 'b', 'x', 'z', 'y'};
char[] b = new char[]{'r', 's', 't', 'a', 'b'};
boolean isSuccessive = false;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < b.length - 1; j++) {
if (a[i] == b[j] && a[i + 1] == b[j + 1]) {
isSuccessive = true;
}
}
}
assertTrue(isSuccessive);
}

Related

Why do I see this weird symbol in place of characters in the char array in java?

output
I'm getting these weird symbols while trying to display this char array. Same problem in online compiler too. what to do?
It happened once to me in C++ too. Either it shows nothing or this. It's making me crazy.
package com.avishkar;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String S = "aeroplane";
char[] arr = new char[S.length()];
for (int i = 0; i < S.length(); i++) {
arr[i] = S.charAt(i);
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr));
int count1 = 0, count2 = 0;
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
count2++;
} else {
count1++;
}
}
char[] con = new char[count1];
char[] vow = new char[count2];
int k = 0, l = 0;
for (int i = 0; i < count1; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
vow[l] = x;
l++;
} else {
con[k] = x;
k++;
}
}
System.out.println(Arrays.toString(con));
System.out.println(Arrays.toString(vow));
int x = 0, y = 0;
char[] finArr = new char[count1 + count2];
for (int i = 0; i < finArr.length; i++) {
if (count1 > count2) {
if (i % 2 == 0) {
finArr[i] = con[x];
x++;
} else {
finArr[i] = vow[y];
y++;
}
} else {
if (i % 2 == 0) {
finArr[i] = vow[y];
y++;
} else {
finArr[i] = con[x];
x++;
}
}
}
String ans = "";
for (int i = 0; i < finArr.length; i++) {
ans += finArr[i];
}
if (count1 - count2 > 1 || count2 - count1 > 1) {
System.out.println("-1");
}
System.out.println(ans);
}
}
I modified your code to print out the hexadecimal value of the characters, rather than the characters themselves.
The output looks like this:
0 0 0 0
61 61 65 65 0
61 0 61 0 65 0 65 0 0
Your "unprintable" characters are hexadecimal zero, which is unprintable.
Here's the modified code.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String S = "aeroplane";
char[] arr = new char[S.length()];
for (int i = 0; i < S.length(); i++) {
arr[i] = S.charAt(i);
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr));
int count1 = 0, count2 = 0;
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
count2++;
} else {
count1++;
}
}
char[] con = new char[count1];
char[] vow = new char[count2];
int k = 0, l = 0;
for (int i = 0; i < count1; i++) {
char x = arr[i];
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
vow[l] = x;
l++;
} else {
con[k] = x;
k++;
}
}
for (char c : con) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(Arrays.toString(con));
for (char c : vow) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(Arrays.toString(vow));
int x = 0, y = 0;
char[] finArr = new char[count1 + count2];
for (int i = 0; i < finArr.length; i++) {
if (count1 > count2) {
if (i % 2 == 0) {
finArr[i] = con[x];
x++;
} else {
finArr[i] = vow[y];
y++;
}
} else {
if (i % 2 == 0) {
finArr[i] = vow[y];
y++;
} else {
finArr[i] = con[x];
x++;
}
}
}
String ans = "";
for (int i = 0; i < finArr.length; i++) {
ans += finArr[i];
}
if (count1 - count2 > 1 || count2 - count1 > 1) {
System.out.println("-1");
}
for (char c : ans.toCharArray()) {
System.out.print(Integer.toHexString((int) c) + " ");
}
System.out.println();
// System.out.println(ans);
}
}

java word search diagonally

so I've been working on this for hours but i cant seem to figure out how the heck to search through a 2D charr array diagonally. Some context for this, I have figured out how to do the search both vertically and horizontally. Also, I am expected to find words from all 4 directions diagonally (top left -> bottom right/ bottom right -> top left/top right -> bottom left/top right -> bottom left)
Here's what I got so far
public void searchDiagonal() {
char [][] grid = //is a [15][15] array
char[] sample = {'W','O','R','D'}
int startR = 0;
int startC = 0;
int endR = 0;
int endC = 0;
boolean wordFound = false;
int row = 0;
for(int i = grid.length - 1; i >= 0; i--)
{
if(i == grid.length - 1) {
//check the middle diagonal
for(int j = grid.length - 1; j >= 0; j--) {
int index = 0;
if(sample[index] == grid[j][j])
{
startR = j;
startC = j;
if(index == sample.length - 1) {
//word has been found
endR = j;
endC = j;
wordFound = true;
System.out.println("Word found at [" + startR + "][" + startC + "] & ["
+ endR + "][" + endC + "]");
break;
}
index++;
}
if(wordFound)
break;
}
}
}
for(int i = grid.length - 1; i >= 0; i--) {
for(int j = grid.length - 1; j >= 0; j--) {
}
//now i will handle up/down and row will handle left/right [row][i]
if(i == 13) {
row = 14;
}
int index = 0;
if(sample[index] == grid[row][i])
{
if(index == 0) {
startR = row;
startC = i;
}
//first char matches
if(sample.length - 1 == index) {
endR = row;
endxC = i;
wordFound = true;
SSystem.out.println("Word found at [" + startR + "][" + startC + "] & ["
+ endR + "][" + endC + "]");
break;
}
index++;
}
row--;
}
}
Thank you in advanced!
To find out 4 diagonal words i would try following
Find TopLeftBottomRight word
reverse it
Find TopRightBottomLeft word
reverse it
find the sample word in above word lists.
Working code for find all 4 diagonal words
public class Main {
public static void main(String[] args) {
char[][] testData = {{'a', 'b', 'c', 'd'}, {'e', 'c', 'b', 'e'}, {'h', 'g', 'a', 'm'}, {'w', 'x', 'z', 't'}};
char[] sample = {'c', 'a', 't'};
boolean result = findInDiagonalWords(diagonalWords(testData),sample);
System.out.println(result);
}
private static List<String> diagonalWords(char[][] testData) {
String first = topLeftBottomRight(testData);
StringBuilder sb = new StringBuilder();
sb.append(first);
String second = sb.reverse().toString();
String third = bottomLeftTopRight(testData);
StringBuilder sb1 = new StringBuilder();
sb1.append(third);
String fourth = sb1.reverse().toString();
return Arrays.asList(first, second, third, fourth);
}
private static String topLeftBottomRight(char[][] testData) {
String topLeftBottomRight = "";
for (int i = 0; i < testData.length; i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
topLeftBottomRight = topLeftBottomRight + testData[i][j];
}
}
}
return topLeftBottomRight;
}
private static String bottomLeftTopRight(char[][] testData) {
String bottomLeftTopRight = "";
for (int i = testData.length; i > 0; i--) {
for (int j = 0; j < testData.length; j++) {
if ((testData.length - i) == j) {
bottomLeftTopRight = bottomLeftTopRight + testData[i - 1][j];
break;
}
}
}
return bottomLeftTopRight;
}
private static boolean findInDiagonalWords(List<String> diagonalWords, char[] sample) {
// return true if sample lies in diagonal words
//return false;
}
}

Loop structure for histogram

I'm trying to write a Java program that generates a histogram of asterisks for each occurrence of a value in an array.
If the elements are, respectively, 0,1,2,3,4,5,6,7,8,9 the output should have an asterisk for each occurrence. For example,
0:*
1:*
2:*
3:*
4:*
5:*
6:*
7:*
8:*
9:*
However, my output is
0:**********
1:
2:
3:
4:
5:
6:
7:
8:
9:
The following code below is my own.
public static void drawHistogram(double[] array) {
String count = "";
for (int i = 0; i < array.length; i++) {
if (array[i] >= 0 && array[i] < 1) {
count += "*";
} else if (array[i] >= 1 && array[i] < 2) {
count += "*";
} else if (array[i] >= 2 && array[i] < 3) {
count += "*";
} else if (array[i] >= 3 && array[i] < 4) {
count += "*";
} else if (array[i] >= 4 && array[i] < 5) {
count += "*";
} else if (array[i] >= 5 && array[i] < 6) {
count += "*";
} else if (array[i] >= 6 && array[i] < 7) {
count += "*";
} else if (array[i] >= 2 && array[i] < 8) {
count += "*";
} else if (array[i] >= 2 && array[i] < 9) {
count += "*";
} else if (array[i] >= 9 && array[i] < 10) {
count += "*";
} else if (array[i] >= 10 && array[i] < 11) {
count += "*";
}
}
for (int j = 0; j <= 10; j++) {
System.out.print(j + count);
count = "";
System.out.println();
}
}
How can I fix this issue?
This solution uses (int) Math.floor(array[i]) to choose the bracket into which to put the double value, thus getting rid of the multiple if-then-else statements. I've also used StringBuilder instead of String to make the repeated concatenation of asterisks a little more efficient.
public static void drawHistogram(double[] array) {
StringBuilder histoGram[] = new StringBuilder[11];
for (int i = 0; i < histoGram.length; i++) {
histoGram[i] = new StringBuilder();
}
for (int i = 0; i < array.length; i++) {
int bracket = (int) Math.floor(array[i]);
if (bracket >= 0 && bracket < histoGram.length) {
histoGram[bracket].append("*");
}
}
for (int j = 0; j < 11; j++) {
System.out.format("%02d: %s\n", j, histoGram[j].toString());
}
}
Test main method:
public static void main(String args[]) {
double[] testValues = new double[100];
for (int i = 0; i < 100; i++) {
testValues[i] = Math.random() * 11.0;
}
drawHistogram(testValues);
}
Sample output:
00: *******
01: ********
02: ***********
03: ************
04: ********
05: **********
06: *******
07: ********
08: **********
09: ************
10: *******
public static void drawHistogram(double[] array) {
String count[] = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] >= 0 && array[i] < 1) {
count[0] = "*";
} else if (array[i] >= 1 && array[i] < 2) {
count[1] = "*";
} else if (array[i] >= 2 && array[i] < 3) {
count[2] = "*";
} else if (array[i] >= 3 && array[i] < 4) {
count[3] = "*";
} else if (array[i] >= 4 && array[i] < 5) {
count[4] = "*";
} else if (array[i] >= 5 && array[i] < 6) {
count[5] = "*";
} else if (array[i] >= 6 && array[i] < 7) {
count[6] = "*";
} else if (array[i] >= 2 && array[i] < 8) {
count[7] = "*";
} else if (array[i] >= 2 && array[i] < 9) {
count[8] = "*";
} else if (array[i] >= 9 && array[i] < 10) {
count[9] = "*";
} else if (array[i] >= 10 && array[i] < 11) {
count[10] = "*";
}
}
for (int j = 0; j <= 10; j++) {
System.out.print(j + count[j]);
System.out.println();
}
}
It seems that you are using only a single variable to count up the occurrences of numbers in this method. This results in you program showing that 0 has nine occurrences and the rest of the numbers have 0 occurrences. I agree with the user David Choweller in the comments, who suggested that you could use an array to solve this problem. However, another solution might be a HashMap, where you store the number as the key, and the string that you want to print out as the value. Then, you can use the loop through the numbers at the end as you do currently, and print out the values associated with them.
You can use a Java Hasmap :
int myArray[] = new int[]{1, 2, 1, 3, 3, 1, 2, 1, 5, 1};
public static void main (String args[]) {
HashMap<Integer, String> hash = new HashMap<>();
hash.put(5, "");
hash.put(4, "");
hash.put(3, "");
hash.put(2, "");
hash.put(1, "");
for (int i = 0; i < myArray.length; i++){
hash.put(new Integer(myArray[i]), hash.get(myArray[i])+"*");
}
for(Integer key: hash.keySet()){
System.out.println(key+": "+ hash.get(key));
}
}

java - understanding a piece of code in array

why i need to write:
mat.length-1
in the second for loop (the loop it all conditions).
the loop:
for (int i = 0; i < mat.length-1; i++) {
for (int j = 0; j < mat.length-1; j++) {
if (i == j) {
j++;
if (i == mat.length - 1 && j == mat.length - 1) {
break;
}
}
if (i != j && mat[i][j] == mat[j][i]) {
flag = true;
} else {
flag = false;
if (flag == false) {
stop = 1;
i = mat.length - 1;
}
}
}
}
Checking program applies
Complete code:
public class test {
public static void main(String[] args) {
//int[][] mat = { { 9, 2, 4 }, { 2, 9, 7 }, { 4, 7, 9 } };
int[][]mat = { { 9, 2, 3, 4},
{ 2, 9, 6, 3},
{ 3, 6, 9 ,2},
{ 4, 3, 2 ,9}};
boolean flag = true;
int stop = 0;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
System.out.print("[" + mat[i][j] + "]");
}
System.out.println();
}
for (int i = 0; i < mat.length-1; i++) {
for (int j = 0; j < mat.length-1; j++) {
if (i == j) {
j++;
if (i == mat.length - 1 && j == mat.length - 1) {
break;
}
}
if (i != j && mat[i][j] == mat[j][i]) {
flag = true;
} else {
flag = false;
if (flag == false) {
stop = 1;
i = mat.length - 1;
}
}
}
}
if (stop == 1) {
System.out.println("Not first folded matrix");
} else {
System.out.println("First folded matrix");
}
}
}
this is work but if i change it to
mat.length
It does not work
If I write a negative one then it stops the loop of the i before it reaches the end of the array.
Can explanation?
In your code, these lines serve no purpose as i and j would never be equal to (mat.length-1) in your code.
if (i == mat.length - 1 && j == mat.length - 1) {
break;
}
Change your code to :
for (int i = 0; i < mat.length; i++) {
for (int j = i+1; j < mat.length; j++) {
if (mat[i][j] != mat[j][i]) {
flag = false;
j = mat.length;
i = mat.length;
}
}
}
if (flag == false) {
System.out.println("Not first folded matrix");
} else {
System.out.println("First folded matrix");
}

Making a hollow diamond with a word in it

What I need is a little modification to my code so that every part of my hollow diamond prints a letter of the word "HURRICANE"
My code is:
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
The output comes out as:
H
H H
H H
H H
H H
H H
H H
H H
H
I need to modify my "charAt" statement a little so it comes out to be:
H
U U
R R
R R
I I
C C
A A
N N
E
How should I make my print statement?
It's worth noting that the example provided only works for Strings the same length as "HURRICANE". A superior solution would work for all strings.
Partial solution for you to complete, since I guess it's your coursework and I don't want you to copy / paste / fail exams :P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i)
+ st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(5 - i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(3 + i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
Let's assume that a word has an odd number of characters, otherwise we get a crooked diamond.
Try it online!
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
Output:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a

Categories