prog_tk prog_tk - 4 months ago 11
Java Question

I cannot get the program to repeat output in an ordered manner

I want to design a program which scales strings. if string d = "abc\ndef\nghi",horizontal scalling=2,vertical scalling=2, then scaleObj.scale(d,2,2)/defined below/ should output "aabbcc\naabbcc\nddeeff\nddeeff\ngghhii\ngghhii".

//output

aabbcc
aabbcc
ddeeff
ddeeff
gghhii
gghhii


ive have a problem which ive defined below:

//MainSix.java

public class MainSix{
public static void main(String[] args){
Scale scaleObj = new Scale();
System.out.println(scaleObj.scale("abc\ndef",2,3));
}

}

class Scale {

public static String scale(String strng, int k, int v) {

//Horizontal Scalling -k
String s=strng.replaceAll(".", repeat("$0",k));

//Verical Scalling
String y = repeat(s,v);

return y;

}
public static String repeat(String str, int times){
return new String(new char[times]).replace("\0", str);
}
}


When i Compile this i get output

aabbcc
ddeeffaabbcc
ddeeffaabbcc
ddeeff

//aabbcc\nddeeffaabbcc\n\nddeeffaabbcc\nddeeff


How can i get output

aabbcc
aabbcc
aabbcc
ddeeff
ddeeff
ddeeff

//aabbcc\naabbcc\n\naabbcc\nddeeffddeeff\nddeeff


Please modify this existing code

Answer

if you want abc\ndef to be equal to aabbcc\nddeeff if the scale is set to 2.

You could split the string into token(chars), then replace each char with it self times the scale factor.

a would be replaced with aa, b => bb, c => cc, etc

In the example below i just create a new string with the output, instead of replacing values in the input (its mostly preference).

int scale = 2;
String s = "abc", ss = "";
for (char c : s.toCharArray()) { 
  for (int i = 0; i < scale; i++) {
    ss += c;
  }
}
System.out.println(ss); //ss = aabbcc

EDIT1:

int scale = 2, rpt = 3;
String s = "abc\ndef", ss = "";
for (String t : s.split("\n")) { //Word loop
  for (int j = 0; j < rpt; j++) { //Repeat loop
    for (char c : t.toCharArray()) { //Char loop
      for (int i = 0; i < scale; i++) { //Scale loop
        ss += c;
      }
    }
    ss += "\n";
  }
}
System.out.println(ss); 
/*
aabbcc
aabbcc
aabbcc
ddeeff
ddeeff
ddeeff
*/