How to rearrange the columns in a 2d array matrix alphabetically - java

I want to take the following matrix below and rearrange the chars TOAD to ADOT and the rearrange the corresponding columns below to where the char above moved, so for example A moved to col 0 so now VGD should all be in col 0 etc.
TOAD is a separate array by the way! im using that keyword to sort the martrix alphabetically.
//Matrix output and then the code.
T O A D
V V V X
D V G G
D F D V
public String printMatrix(String s [][]){
char key[] = polyCipher.getKeyword().toCharArray();
String keyOut = "";
for(int i=0;i<key.length;i++){
keyOut += key[i] + " ";
}
keyOut += "\n";
for (int i = 0; i < s.length; i++) {
// keyOut += PHRASE_KEY[i] + " ";
for (int j = 0; j < s[i].length; j++) {
keyOut += s[i][j] + " ";
}
keyOut += "\n";
}
return keyOut.toUpperCase();
}
public static String [][] buildMatrix (String translation, String outermarker, String innermarker) {
// outerdelim may be a group of characters
String [] sOuter = translation.split("[" + outermarker + "]");
int size = sOuter.length;
// one dimension of the array has to be known on declaration:
String [][] result = new String [size][size];
int count = 0;
for (String line : sOuter)
{
result [count] = line.split (innermarker);
++count;
}
return result;
}
public void sortArray(){
// do tomorrow
}
public String matrixFormatter(String x){
String resultstr = "";
int i = 0;
while(i < x.length()) {
// If end of string: only add character.
if (i == x.length() - 1) {
resultstr += x.substring(i, i + 1);
} else {
if ( ((i + 1) % 4) == 0) {
resultstr += x.substring(i, i + 1) + "|";
} else {
resultstr += x.substring(i, i + 1) + ",";
}
}
i++;
}
return resultstr;
}
}

Related

Converting Binary to Decimal Numbers in Java strictly using multiplication and division

I am trying to get my Binary to Decimal method to calculate properly. I have to use the multiply and/or divide methods in the "bToD" method. I can't figure out how to get it return the answer correct. It should only be returning "5", but instead it is returning 45. I need to fix this method in order to continue the remaining Hexadecimal to Binary and Octal to Binary methods.
package numType;
import java.util.Scanner;
public class numType{
public static String multiply2(String n) { //return 2*n
String r = "";
int c = 0;
for (int i = n.length()-1; i >= 0; i--) {
int p = (n.charAt(i)-'0')*2+c;
c = p/10;
r = p%10+r;
}
if (c > 0)
r = c+r;
return r;
}
public static String divide2(String n) { //return n/2
String r = "";
int b = 0;
int i = 0;
if (n.charAt(0) < '2') {
b = 1;
i = 1;
}
for (; i < n.length(); i++) {
int p = (n.charAt(i)-'0')+b*10;
b = p%2;
r += p/2;
}
if (r.length() == 0)
r = "0";
return r;
}
//convert binary string b to an equivalent decimal string.
public static String bToD(String b)
{
String s = "";
int n = 0;
if (b.charAt(b.length()-1) == '1')
n = 1;
else
n = 0;
int pow = 1; //INITIALIZE POWER # FROM THE SECOND TO LAST 2^1
for (int i=b.length()-2; i>=0; i--) // LIST #'S FROM MOST RIGHT-HAND SIDE
{
char ch = b.charAt(i);
String temp = "" + ch;
for (int j=1; j<=pow; j++)
temp = multiply2(temp);
//System.out.println(temp);
int n1 = 0;
for (int k=0; k<temp.length(); k++)
{
n1 = n1*10 + (int) (temp.charAt(k)-'0');
}
n = n + n1;
s = temp;
pow++;
}
s = s + n;
return s;
}
//convert decimal string d to an equivalent binary string.
public static String dToB(String d)
{
String s = "";
while (!d.equals("0"))
{
String d1 = divide2(d);
d1 = multiply2(d1);
if (d1.equals(d))
s = "0" + s;
else
s = "1" + s;
d = divide2(d);
}
return s;
}
//convert binary string b to an equivalent octal string.
public static String bToO(String b)
{
String s = "";
int groups = b.length()/3;
int index = 0;
//System.out.println(index); //bToD(b)
while (groups != index)
{
for (int i = b.length()-3; i >= 0; i--)
{
for (int j=1; j<=i; j++)
{
String temp = b.substring(b.length()-3,b.length()); //last 3 digits in binary
String sSub = b.substring(0,b.length()-3); //first digits in binary
s = bToD(temp);
}
}
index++;
}
return s;
}
//convert octal string o to an equivalent binary string.
public static String oToB(String o)
{
String s ="";
int digits = o.length();
int index = 0;
while (digits != index)
{
for (int i=o.length()-1; i>=0; i--)
{
char ch = o.charAt(i);
//System.out.println(digits);
switch (ch)
{
case '7':
s = s + "111";
index++;
break;
case '6':
s = s + "110";
index++;
break;
case '5':
s = s + "101";
index++;
break;
case '4':
s = s + "100";
index++;
break;
case '3':
s = s + "011";
index++;
break;
case '2':
s = s + "010";
index++;
break;
case '1':
s = s + "001";
index++;
break;
case '0':
s = s + "000";
index++;
break;
}
}
}
return s;
}
//convert binary string b to an equivalent hexadecimal string.
public static String bToH(String b)
{
String s ="";
return s;
}
//convert hexadecimal string h to an equivalent binary string.
public static String hToB(String h)
{
String s ="";
return s;
}
public static void main(String[] args) {
// TODO code application logic here
String b,d,o,h;
b = "101";
System.out.println("Binary to Decimal:");
System.out.println(b + " => " + bToD(b));
System.out.println();
System.out.println("Decimal to Binary:");
d = "45";
System.out.println(d + " => " + dToB(d));
System.out.println();
System.out.println("Binary to Octal:");
b = "100101101";
System.out.println(b + " => " + bToO(b));
System.out.println();
System.out.println("Octal to Binary:");
o = "";
System.out.println(o + " => " + oToB(o));
System.out.println();
System.out.println("Binary to Hexadecimal:");
b = "";
System.out.println(b + " => " + bToH(b));
System.out.println();
System.out.println("Hexadecimal to Binary:");
h = "";
System.out.println(h + " => " + hToB(h));
}
}
Here's a solution, yours is quite convoluted.
//convert binary string b to an equivalent decimal string.
public static String bToD(String b)
{
int ans = 0, pow = 0;
//For every digit in binary
for(int i=b.length()-1; i>=0; i--){
// Get string of current char
String cur = Character.toString(b.charAt(i));
for (int j=0; j<pow; j++)
cur = multiply2(cur);
ans += Integer.parseInt(cur);
pow++;
}
return Integer.toString(ans);
}

TitleCase Exercise using JAVA

I just need clarification on this one.
I'm doing a certain exercise on java--
Write a static method that will replace all the first letter
of every word in a String with capital letters.
Example: a string is just a string ----> A String Is Just A String
I was able to accomplish the desired output but I got confused on this part of my code.
THIS SEEMS TO WORK:
char j;
if (length > 1) {
for (int i = 0; i < length; i++) {
j = str2.charAt(i);
if (j == ' ') {
str = str + j + (Character.toUpperCase(str2.charAt(i + 1)));
i++; // for skip
} else {
str = str + j;
}
}
} else {
str = "Please enter a string.";
}
HOWEVER, WHEN I PUT IT THIS WAY IT DOESN’T SEEM TO WORK:
Char j, k;
if (length > 1) {
for (int i = 0; i < length; i++) {
j = str2.charAt(i);
k = str2.charAt(i + 1);
if (j == ' ') {
str = str + j + (Character.toUpperCase(k));
i++; // for skip
} else {
str = str + j;
}
}
} else {
str = "Please enter a string.";
}
Can someone please explain why? Did I miss or overlook something?
Here's the whole code by the way:
package exercises.exercisesday3.part1;
import java.util.Scanner;
public class Exercise5CapitalLetters {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter source String: ");
String capital = myTitleCase(" " + input.nextLine());
System.out.println(capital);
input.close();
}
public static String myTitleCase(String capitalLetter) {
String str = "";
String str2 = capitalLetter.replaceAll("\\s+", " ");
int length = str2.length();
char j;
if (length > 1) {
for (int i = 0; i < length; i++) {
j = str2.charAt(i);
if (j == ' ') {
str = str + j + (Character.toUpperCase(str2.charAt(i + 1)));
i++; // for skip
} else {
str = str + j;
}
}
} else {
str = "Please enter a string.";
}
return str.trim();
}
}
That is due to the incorrect way of reading the value for k as k = str2.charAt(i + 1) it should be changed as show in below code.
In your code try to access the character beyond the length of the String provided.
This should be the corrected code
char j, k=0;
if (length > 1) {
for (int i = 0; i < length; i++) {
j = str2.charAt(i);
if(i!=length-1){
k = str2.charAt(i + 1);
}
if (j == ' ') {
str = str + j + (Character.toUpperCase(k));
i++; // for skip
} else {
str = str + j;
}
}
} else {
str = "Please enter a string.";
}

Replacing a string parameter with a List for a recursive method

I was struggeling with a probably simple problem for the last 3 hours. I rewrote a class and replaced 2 String parameters with Lists.
The problem is, that when calling the rekursive method you add 1 character to the first string parameter. And when the length of the parameter hits the length of 7 it prints it out. The string never gets longer than 7.
I replaced it with a Integer List since the String only consisted of numbers.
The List though keeps getting longer and longer and I have no idea why. I hope I explained everything properly. If not, ask me please.
The question is probably super easy to answer for you guys.
Here is the first class, that works.
package Uebung4;
public class PermAll_Alt {
static int counter = 0;
private static void permutation(String word, String str) {
int n = str.length();
// System.out.println(str + " Str");
// System.out.println(word + " word");
if (n == 0) {
if (
(Integer.parseInt(word.substring(0, 1))) > (Integer.parseInt(word.substring(1, 2)))
&& (Integer.parseInt(word.substring(1, 2))) < (Integer.parseInt(word.substring(2, 3)))
&& (Integer.parseInt(word.substring(2, 3))) > (Integer.parseInt(word.substring(3, 4)))
&& (Integer.parseInt(word.substring(3, 4))) < (Integer.parseInt(word.substring(4, 5)))
&& (Integer.parseInt(word.substring(4, 5))) > (Integer.parseInt(word.substring(5, 6)))
&& (Integer.parseInt(word.substring(5, 6))) < (Integer.parseInt(word.substring(6, 7)))
) {
// System.out.println(word);
counter++;
}
} else {
for (int i = 0; i < n; i++) {
// System.out.println("Word: " +word+"\t str charat:
// "+str.charAt(i));
// System.out.println(word + str.charAt(i) + " \t combined");
System.out.println("substr(0,i): " + str.substring(0, i) + " substr(i+1) " + str.substring(i + 1));
permutation(word + str.charAt(i), str.substring(0, i) + str.substring(i + 1));
}
}
}
public static void main(String[] args) {
permutation("", "1234567");
System.out.println("Anzahl: " + counter);
}
}
And here is my class that I edited:
package Uebung4;
import java.util.ArrayList;
import java.util.List;
public class PermAll {
static int counter = 0;
private static void permutation(List<Integer> wordList, List<Integer> lis) {
// List<Integer> wordList2 = cloneList(wordList);
int n = lis.size();
if (n == 0) {
String word = "";
for (Integer i : wordList) {
word += i;
}
if ((Integer.parseInt(word.substring(0, 1))) > (Integer.parseInt(word.substring(1, 2)))
&& (Integer.parseInt(word.substring(1, 2))) < (Integer.parseInt(word.substring(2, 3)))
&& (Integer.parseInt(word.substring(2, 3))) > (Integer.parseInt(word.substring(3, 4)))
&& (Integer.parseInt(word.substring(3, 4))) < (Integer.parseInt(word.substring(4, 5)))
&& (Integer.parseInt(word.substring(4, 5))) > (Integer.parseInt(word.substring(5, 6)))
&& (Integer.parseInt(word.substring(5, 6))) < (Integer.parseInt(word.substring(6, 7)))
) {
System.out.println(word);
// convertToDU(word);
counter++;
}
} else {
for (int i = 0; i < n; i++) {
List<Integer> tempLis = new ArrayList<>();
//String tempString = "";
for (int j = 0; j < i; j++) {
tempLis.add(lis.get(j));
}
System.out.print("str.substr(0,i): " + tempLis+"\t");
for (int k = i + 1; k < lis.size(); k++) {
tempLis.add(lis.get(k));
System.out.print(""+lis.get(k)+", ");
}
System.out.println(tempLis);
// System.out.println("word "+wordList + "\t charat:
// "+lis.get(i));
wordList.add(lis.get(i));
// System.out.println(wordList + " \t kombiniert");
permutation(wordList, tempLis);
// permutation(word + lis.get(i),tempLis);
}
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
int anzahl = 7;
for (int i = 1; i <= anzahl; i++) {
list.add(i);
}
String para = "";
for (Integer i : list) {
para += i;
}
List<Integer> abc = new ArrayList<>();
permutation(abc, list);
System.out.println("Anzahl: " + counter);
}
}
Here is a solution: I took the code that was doing the recursive call in the String args version and copied the logic to the List args version:
for (int i = 0; i < n; i++) {
// create a copy of wordList
List<Integer> permWordList = new ArrayList<Integer>(wordList);
// equiv to "word + str.charAt(i)"
permWordList.add(strLis.get(i));
// create a copy of lis
List<Integer> permStrList = new ArrayList<Integer>(lis);
// equiv to "str.substring(0, i) + str.substring(i + 1)"
permStrList.remove(i);
permutation(permWordList, permStrList);
}

java.lang.StringIndexOutOfBoundsException: String index out of range: 7

I don't really know how to program... I was working on this for a Computer Science Class
Instruction: Use nested loops to print out the square word pattern show below.
I'm guessing the error is in the toString method, but I can't spot where.
the desired output is: (when input is SQUARE)
SQUARE
Q R
U A
A U
R Q
ERAUQS
The code:
import static java.lang.System.*;
class BoxWord
{
private String word;
public BoxWord()
{
word="";
}
public BoxWord(String s)
{
setWord(s);
}
public void setWord(String w)
{
word=w;
}
public String toString()
{
String output=word +"\n";
for(int i =0;i<word.length(); i++){
output += word.charAt(i);
for(int j = 2; j<word.length();j++)
output += " ";
output+= word.charAt(word.length()-(i-1))+ "\n";
}
for(int k=0; k<word.length(); k++)
output+= word.charAt(k);
return output+"\n";
}
}
main:
import static java.lang.System.*;
public class Lab11f
{
public static void main( String args[] )
{
BoxWord test = new BoxWord("square");
out.println(test);
}
}
Try the following, I will explain the modifications in comments:
public static void main(String[] args)
{
String word = "square";
String output = word + "\n"; // Initialize with the word
for (int i = 1; i < word.length() - 1; i++) { // From '1' to 'length - 1' because we don't want to iterate over the first and last characters
output += word.charAt(i);
for (int j = 0; j < word.length() - 2; j++) // To add spaces
output += " ";
output += word.charAt(word.length() - (i + 1)) + "\n";
}
for (int k = word.length() - 1; k >= 0; k--) // Add word in reverse
output += word.charAt(k);
System.out.println(output);
}
Output:
square
q r
u a
a u
r q
erauqs
On the first two iterations of this loop you are going to have an error:
for(int i =0;i<word.length(); i++){
output += word.charAt(i);
for(int j = 2; j<word.length();j++)
output += " ";
output+= word.charAt(word.length()-(i-1))+ "\n";
^^^^^^^^^^^^^^^^^^^
}
This is equivalent to word.length() - i + 1 which is going to be an error when i is 0 or 1.
public String toString()
{
String output=word +"\n";
for(int i =0;i<word.length(); i++){
output += word.charAt(i);
for(int j = 2; j<word.length();j++)
output += " ";
output+= word.charAt(word.length()-(i-1))+ "\n";
}
output+= word.charAt(word.length()-(i-1))+ "\n"; this line is making string index out of bound exception

UVa 630 kept getting wrong answer [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have been working on the UVa 630 problem for 2 days, http://acm.uva.es/p/v6/630.html
I have written a working code, however constantly getting the wrong answer result after the submission, my program works fine for the given input format and generate correct result, could someone please take a look at my code and find what's wrong with it please.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
class Main {
String[] init;
String[] sorted;
int voca = 0;
String[] test;
private String x;
private String y;
ArrayList<ArrayList> initial = new ArrayList<ArrayList>();
char[] charArray;
String input;
void initSort(String i) {
input = i;
charArray = input.toCharArray();
}
char[] get() {
return charArray;
}
void sort(int low, int high) {
int i = low;
char pivot = charArray[low];
for (int j = low + 1; j < high; j++) {
if (charArray[j] < pivot) {
if (j > i + 1) {
exchange(i + 1, j);
}
i++;
}
}
exchange(low, i);
if (i > low + 1)
sort(low, i);
if (i + 2 < high)
sort(i + 1, high);
}
void exchange(int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// ********************************************
void begin() {
// System.out.println("begin test");
int numOfdataSet;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
numOfdataSet = Integer.parseInt(in.readLine());
do {
ArrayList currentSet = new ArrayList();
int numberOfdic;
String tempStringV;
String tempStringT;
int i = 0;
try {
String emptyLine = in.readLine();
numberOfdic = Integer.parseInt(in.readLine());
;
currentSet.add(emptyLine);
currentSet.add(Integer.toString(numberOfdic));
// System.out.println("enter numberOfdic is " +
// numberOfdic);
while (i < numberOfdic) {
tempStringV = in.readLine();
currentSet.add(tempStringV);
i++;
}
// System.out.println("input test word");
tempStringT = in.readLine();
currentSet.add(tempStringT);
while (!tempStringT.equals("END")) {
tempStringT = in.readLine();
currentSet.add(tempStringT);
}
} catch (IOException e) {
e.printStackTrace();
}
initial.add(currentSet);
numOfdataSet--;
} while (numOfdataSet != 0);
} catch (IOException e) {
}
;
print();
}
// ***************************************************
void getArrays(ArrayList<String> a) {
// read the file and put the words into a temporary array
String[] temp = new String[a.size()];
for (int i = 0; i < a.size(); i++) {
temp[i] = a.get(i);
// System.out.println("temp "+i+" is "+temp[i]);
}
// extract the vocabulary counter from the temp array
int vocaCounter;
int shift;
if (!temp[0].equals("")) {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
} else {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
}
// System.out.println("there are "+vocaCounter);
// store the vocabulary into the array named as init
init = new String[vocaCounter];
for (int i = shift; i < vocaCounter + shift; i++) {
init[i - shift] = temp[i];
// System.out.println(i - shift + " voca is " + init[i - shift]);
}
// store the test words into the array named as test
test = new String[temp.length - vocaCounter - shift - 1];
for (int j = 0; j < temp.length - vocaCounter - shift - 1; j++) {
test[j] = temp[j + vocaCounter + shift];
// System.out.println("test "+j+" is "+test[j]);
}
sorted = init;
}
/**
* sort the two strings
*/
void arraySorter() {
x = x.toLowerCase();
initSort(x);
sort(0, x.length());
get();
// java.util.Arrays.sort(FirstArray);
y = y.toLowerCase();
initSort(y);
sort(0, y.length());
get();
}
String getEle(String in) {
initSort(in);
sort(0, in.length());
return new String(get());
}
void print() {
Iterator<ArrayList> iterator = initial.iterator();
while (iterator.hasNext()) {
getArrays((ArrayList<String>) iterator.next());
// ****************
/**
* sort the test array and store it as the testSort array
*/
String[] testSort = new String[test.length];
for (int i = 0; i < test.length; i++) {
testSort[i] = test[i];
}
for (int i = 0; i < test.length; i++) {
testSort[i] = getEle(testSort[i]);
}
// for(int i=0;i<test.length;i++)
// {
// System.out.println("test is "+test[i]+" and test sorted is "+testSort[i]);
// }
/**
* sort the vocabulary array and store the sorted array as vocaSort
*/
String[] vocaSort = new String[init.length];
for (int i = 0; i < init.length; i++) {
vocaSort[i] = init[i];
}
for (int i = 0; i < init.length; i++) {
vocaSort[i] = getEle(vocaSort[i]);
}
// start the testing process
for (int i = 0; i < test.length; i++) {
int counter = 1;
System.out.println("Anagrams for: " + test[i]);
for (int j = 0; j < sorted.length; j++) {
// anagramTester(test[i], init[j]);
boolean result = testSort[i].equals(vocaSort[j]);// //AnagramTester();
if (result == true && counter < 10) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 100) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 1000) {
System.out.println("" + counter + ") " + init[j]);
counter++;
}
}
if (counter == 1)
System.out.println("No anagrams for: " + test[i]);
}
System.out.println();
}
}
/**
* main function
*
* #param args
*/
public static void main(String[] args) {
Main myWork = new Main(); // create a dinamic instance
myWork.begin();
}
}
below is the input.txt file
1
4
atol
lato
rola
tara
kola
tola
END
2
24
uhgj
uhjg
ughj
ugjh
ujhg
ujgh
hujg
hugj
hgju
hguj
hjgu
hjug
guhj
gujh
ghuj
ghju
gjuh
gjhu
jugh
juhg
jhgu
jhug
jghu
jguh
jguh
END
it was a output format issue and problem solved

Categories

Resources