How to achieve array two-column exchange? - java

We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
all code
package ubung;
import java.util.Random;
//-------------------------------------------------------------- a)
public class Sudoku {
final int n = 3;
final int gridsize = n*n;
int[][] field = new int[gridsize][gridsize];
Random random = new Random();
public Sudoku() {
int[] firstRow = {1,2,3,4,5,6,7,8,9};
//h): int[] firstRow = randomRow();
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
field[i][j] = (i*n + i/n + j) % gridsize + 1;
//h): field[i][j] = firstRow[(i*n + i/n + j) % gridsize];
System.out.println(this);
}
//------------------------------------------------------------- g)
public Sudoku(int permutationCount) {
this();
randomPermutation(permutationCount);
}
//-------------------------------------------------------------- b)
/**Die Methode gibt ein Sudoku-Objekt als einen String zurueck
* #return der String eines Sudoku-Objektes
*/
public String toString() {
String str = line(25);
for(int i = 0; i < 9; i++){
str += "|";
for(int j = 0; j < 9; j++){
str += " " + get(i,j);
if(j == 2 || j == 5 || j == 8)
str += " |";
}
str += "\n";
if(i == 2 || i == 5 || i == 8){
str += line(25);
}
}
return str;
}
/**
* Getter for single entries
*/
private String get(int i, int j) {
if(i < 0 || i > gridsize + 1 || j < 0 || j > gridsize + 1) {
return " ";
}
int m = field[i][j];
if(m == 0)
return " ";
return ""+m;
}
private String line(int n){
String str = "";
for(int i = 0; i < n; i++)
str += "-";
return str+"\n";
}
//-------------------------------------------------------------- c)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions. ?????????????????????????
*/
private void permutateRows(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
for(int i = 0; i < gridsize; i++) {
int temp = field[i][a-1];
field[i][a-1] = field[i][b-1];
field[i][b-1] = temp;
}
}
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions. ????????????????????
*/
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
//-------------------------------------------------------------- d)
/**
* Two stacks are swapped. This produces 3! as much solutions.
*/
private void permutateStacks(int a, int b) {
if(b < a) {
permutateStacks(b,a);
return;
}
if(a == 1 && b == 2) {
permutateColumns(1,4);
permutateColumns(2,5);
permutateColumns(3,6);
}
else if(a == 1 && b == 3) {
permutateColumns(1,7);
permutateColumns(2,8);
permutateColumns(3,9);
}
else if(a == 2 && b == 3) {
permutateColumns(4,7);
permutateColumns(5,8);
permutateColumns(6,9);
}
}
/**
* Two bands are swapped. This produces 3! as much solutions.
*/
private void permutateBands(int a, int b) {
if(b < a) {
permutateBands(b,a);
return;
}
if(a == 1 && b == 2) {
permutateRows(1,4);
permutateRows(2,5);
permutateRows(3,6);
}
else if(a == 1 && b == 3) {
permutateRows(1,7);
permutateRows(2,8);
permutateRows(3,9);
}
else if(a == 2 && b == 3) {
permutateRows(4,7);
permutateRows(5,8);
permutateRows(6,9);
}
}
//-------------------------------------------------------------- e)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions.
*/
private void permutateRows() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateRows(a+block*3,b+block*3);
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions.
*/
private void permutateColumns() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateColumns(a+block*3,b+block*3);
}
private void permutateStacks() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateStacks(a,b);
}
private void permutateBands() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateBands(a,b);
}
//-------------------------------------------------------------- f)
/**
* The matrix is transposed. This produces double as much solutions.
*/
private void transpose() {
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < i; j++) {
int temp = field[j][i];
field[j][i] = field[i][j];
field[i][j] = temp;
}
}
//-------------------------------------------------------------- g)
private void randomPermutation(){
switch(random.nextInt(5)) {
case 0: permutateRows(); break;
case 1: permutateColumns(); break;
case 2: permutateStacks(); break;
case 3: permutateBands(); break;
case 4: transpose();
default:
}
}
private void randomPermutation(int n){
for(int i = 0; i < n; i++)
randomPermutation();
}
//-------------------------------------------------------------- h)
/**
* Returns random row of digits. Used to relabel digits in the initial matrix
* This yields 9! as much solutions.
*/
private int[] randomRow(){
boolean[] used = new boolean[gridsize];
int[] row = new int[gridsize];
for(int i = 0; i < gridsize; i++) {
int candidate = random.nextInt(gridsize);
if(!used[candidate]){
used[candidate] = true;
row[i] = candidate+1;
}
else {
i--;
}
}
return row;
}
//-------------------------------------------------------------- i)
private void hide(int n) {
if(n < 0)
n = 0;
if(n > 81)
n = 81;
for(int k = 0; k < n; k++) {
int i = random.nextInt(9); //在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值。
int j = random.nextInt(9);
if(field[i][j] != 0)
field[i][j] = 0;
else
k--;
}
}
/*****************************************/ //gegeben
public static void main(String[] args){
Sudoku s = new Sudoku(100000);
System.out.println(s);
s.hide(50);
System.out.println(s);
}
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.

If we notate the indices of the 2D array as field[x][y], the provided solution code uses x as the column index and y as the row index. It is important to note that the provided method is not the only correct solution. It would be just as correct to implement x as the row index and y as the column index, so long as the methods were implemented correctly.

Related

Module and how to use it in the situation below

public class AirplaneLab
{
private int [][] first;
private int [][] economy;
private boolean [] seat;
private boolean okay;
private boolean okayokay;
public AirplaneLab()
{
}
public AirplaneLab(int [][] first1, int [][] economy1)
{
}
public boolean viewFirstClass(boolean set[], int [][] first, int [][] economy)
{
if (okay = true)
{
boolean seating1[] = new boolean[20];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if(seat[((j + 1) + (i * 4)) - 1])
{
System.out.print("x ");
seating1[i * j] = true;
}
else
{
System.out.print("o ");
seating1[i * j] = flase;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating1[];
}
else
{
return false;
}
}
public boolean viewEconomyClass(boolean set[], int [][] first, int [][] economy)
{
if (okayokay = true)
{
boolean seating2[] = new boolean[30];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
if(seat[((j + 1) + (i * 3)) - 1])
{
System.out.print("x ");
seating2[i * j] = true;
}
else
{
System.out.print("o ");
seating2[i * j] = false;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating2[];
}
else
{
return false;
}
}
public void decision()
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1 for “booking in first class”");
System.out.println("2 for “booing in economy class”");
System.out.println("3 to view seating chart for first class ");
System.out.println("4 to view seating chart for economy class");
System.out.println("0 to exit");
System.out.print("? ");
while(true)
{
int mOpt = input.nextInt();
if ((mOpt == 1) || (mOpt == 3))
{
if (mOpt == 1)
{
okay = true;
System.out.println("Based on the following setting arrangement, please pick a window middle or end seat");
viewFirstClass(boolean set[], int [][] first, int [][] economy);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (seating1[i * j] == true)
{
if ((i * j) ________________)
}
}
}
}
}
}
}
}
In the code above, where the blank is:
The last if statement before all of the closed brackets:
I was wondering how you would use module there.
Let's say I wanted to do (i * j) module of 4; how would I do that? Can you fill in the blank? Thank you for your help!
If you are looking for some thing (modulo) like
if ((i * j) mod 4 )
in java ,the syntax would be
if ((i * j) % 4 )

Zigzag conversion

Question is : The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
I have written below code, appearantly it works fine, but I might miss some corner cases. Could you help me to find all the corner cases for this question on my answer?
public static String zigZagConversion(String s , int rowNum){
if (s == null){
throw new IllegalArgumentException();
}
if (rowNum == 1){
return s;
}
StringBuilder str = new StringBuilder();
int step = 2 * rowNum - 2 ;
for (int i = 0 ; i < rowNum ; i++){
if( i == 0 || i == rowNum -1){
for (int j = i ; j < s.length() ; j +=step){
str.append(s.charAt(j));
}
}
else{
int step2 = 2* (rowNum - i - 1);
int step3 = step - step2;
int k = i;
boolean flag = true;
while (k < s.length()){
str.append(s.charAt(k));
if(flag){
k += step2;
flag = false;
}
else{
k +=step3;
flag = false;
}
}
}
}
return str.toString();
}
It gives incorrect output for "PAYPALISHIRING", 4
P I N
A L S I G
Y A H R
P I
So the correct answer should be PINALSIGYAHRPI.
But your program gives PINALIGYAIHRNPI:
an "S" is missing, one extra "I" and one extra "N".
Your revised version is still incorrect, it gives PINALSIIGYAHNPI.
The problem is in the while loop in the middle.
You need to alternate the step counting,
setting the flag on and off.
Your mistake was to only set it off once, and never back on again.
str.append(s.charAt(k));
if (flag) {
k += step2;
flag = false;
} else {
k += step3;
flag = true;
}
With this correction, I believe your solution is correct. (I also added a minor improvement there, extracting the common str.append(s.charAt(k)); from the if-else branches.
My solution on leetcode forum:
https://leetcode.com/problems/zigzag-conversion/discuss/549451/Java-Solution-O(n)-with-algorithm
The mathematic algorithm for zigzag is:
originalDiff = numRows * 2 - 2;
If -> 'currRow' equals First or last lines
use the originalDiff (numRows * 2 - 2)
Else ->
For each new line:
upperDiff += 2,
lowerDiff -=2
Examples:
numRows =2 -> originalDiff = 2
PYAIHRN
APLSIIG
3 -> 4
P A H N
A P L S I I G
Y I R
numRows = 4 -> originalDiff = 6
P I N
A L S I G
Y A H R
P I
numRows = 5 -> originalDiff = 8
P H
A SI
Y I R
P L I G
A N
*/
My solution:
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1) {
return s;
}
String newString = "";
int originalDiff = numRows * 2 - 2;
int diff = originalDiff;
int upperDiff = 0;
boolean isGoingDown = true;
int currIndex = 0;
int currRow = 0;
int startingIndex = 0;
for(int i = 0; i < s.length(); i++) {
System.out.println(currIndex);
newString += s.charAt(currIndex);
if(currRow == 0 || currRow == numRows - 1) {
currIndex += originalDiff;
} else {
if(isGoingDown) {
currIndex += diff;
isGoingDown = !isGoingDown;
} else {
currIndex += upperDiff;
isGoingDown = !isGoingDown;
}
}
if(currIndex >= s.length()) {
currRow++;
diff -= 2;
upperDiff += 2;
currIndex = currRow;
isGoingDown = true;
}
if(currRow == numRows) {
i = s.length();
}
}
return newString;
}
}
Zigzag conversion from leetcode in Javascript
Solution
const zigzag = (str, num) => {
if (num === 1) {
return str;
}
let check = true;
let result = [];
let i = 0;
while (i < str.length) {
result.push([]);
let j = 0;
while (j < num) {
if (check){
result[result.length-1].push(str[i]);
i++;
} else {
if (j == 0) {
result[result.length-1].push(null);
} else if (j === num-1) {
result[result.length-1].unshift(null);
} else {
result[result.length-1].unshift(str[i]);
i++;
}
}
j++;
}
check = !check;
}
let zigzag = [];
for (let k = 0; k < num; k++){
for(let l = 0; l < result.length; l++) {
zigzag.push(result[l][k]);
}
}
return zigzag.join("");
}
Example Input
zigzag("ABCD", 3)
Output
ABDC
Run
https://repl.it/#VinitKhandelwal/zigzag-conversion-javascript
Using HashMap
public String convert(String s, int numRows) {
if (numRows == 1){
return s;
}
StringBuilder result = new StringBuilder();
Map<Integer, StringBuilder> map = new HashMap<>();
for (int i = 0; i < numRows; i++) {
map.put(i,new StringBuilder());
}
int it = 0;
boolean flip = true;
for (int i = 0; i < s.length(); i++) {
if (flip) {
if(it<s.length()){
map.get(it).append(s.charAt(i));
it++;
}
} else {
map.get(it).append(s.charAt(i));
it--;
}
if (it + 1 == numRows || it == 0)
flip = !flip;
}
for (Map.Entry entry: map.entrySet()) {
result.append(entry.getValue());
}
return result.toString();
}
My Solution is traversing the string in the same way it is said in the problem, it is better to make string array of size numrows and the rest is storing the string character as it is in the logic,
you can keep the index and when that index is 0 i.e at the starting then we have to go till the end of the row and then except for first and last row, every array will have diagonal element.
So after traversing till the end then assign index = numrows - 2 and save in the respective array string and decrease and do the same till index >0 and then again traverse till the end row, do this and when we reach the end of the string then break from the loop.
and then concate all the string of string array in a new res string.
class Solution {
public String convert(String s, int n) {
if(n==1 || n>=s.length())
return s;
String[] a = new String[n]; //string array
int ind=0; // index for the string array
boolean flag=true;
int cnt=0; //to keep the counter till where we have traversed the string
while(true && flag)
{
if(ind==0)
{
for(int i=0;i<n;i++)
{
a[i] += s.charAt(cnt);
cnt++;
if(cnt==s.length())
{
flag=false;
break;
}
} // here it has reached the end so we assign here
ind = n-2;
}
else if(ind>0 && ind<n && flag)
{
a[ind] += s.charAt(cnt);
cnt++;
if(cnt==s.length())
{
flag=false;
break;
}
ind--; // to move diagonally up
}
}
String res = new String("");
for(int i=0;i<a.length;i++)
{
// System.out.println(a[i].substring(4));
res += a[i].substring(4);
}
return res;
}
}
Following is the simple solution.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows <= 1:
return s
res = ""
p = numRows * 2 - 2
temp = p
for i in range(0,numRows):
index = i
flag = 0
while index < len(s):
res = res + s[index]
if i == 0 or i == numRows-1:
index = index + p
else:
if flag == 0:
index = index + temp
flag = 1
else:
index = index + p-temp
flag = 0
temp = temp - 2
return res
zigzag-conversion Complete JavaScript-based solution
Created an Array of an array of row lengths. The main motive is to arrange characters in 2D array form and concat string row-wise.
var convert = function(s, numRows) {
let array =[],c=0,str='';
for(let row =0; row<numRows ; row++) {
array[row] = new Array();
}
while(c < s.length) {
for(let row =0; row<numRows ; row++) {
if((row+1)%numRows ==0) {
array[row].push(s[c]);
c++;
break;
} else {
array[row].push(s[c]);
c++;
}
}
for(let rr = numRows-2 ; rr>0;rr--) {
array[rr].push(s[c]);
c++;
}
}
for(let row =0; row<numRows ; row++) {
for(let i=0;i<array[row].length;i++){
if(array[row][i]){
str+=array[row][i]
}
}
}
return str
};
convert("PAYPALISHIRING",3)

compare two string in java result in percentage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have to compare two strings which 4000-5000 characters.
I need result in percentage(i.e. 70% - 80% matched), in java.
Kindly suggest me any solution for it.
Regards
Here is the code to compare two strings and getting result in integer form from 0 to 100.
/**
*
* #author WARLOCK
*/
public class LockMatch {
public static void main(String arg[]) {
//---Provide source and target strings to lock_match function to compare--//
System.out.println("Your Strings are Matched="+lock_match("The warlock","The warlock powered by WTPL")+"%");
}
public static int lock_match(String s, String t) {
int totalw = word_count(s);
int total = 100;
int perw = total / totalw;
int gotperw = 0;
if (!s.equals(t)) {
for (int i = 1; i <= totalw; i++) {
if (simple_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 10)) / total) + gotperw;
} else if (front_full_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 20)) / total) + gotperw;
} else if (anywhere_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 30)) / total) + gotperw;
} else {
gotperw = ((perw * smart_match(split_string(s, i), t)) / total) + gotperw;
}
}
} else {
gotperw = 100;
}
return gotperw;
}
public static int anywhere_match(String s, String t) {
int x = 0;
if (t.contains(s)) {
x = 1;
}
return x;
}
public static int front_full_match(String s, String t) {
int x = 0;
String tempt;
int len = s.length();
//----------Work Body----------//
for (int i = 1; i <= word_count(t); i++) {
tempt = split_string(t, i);
if (tempt.length() >= s.length()) {
tempt = tempt.substring(0, len);
if (s.contains(tempt)) {
x = 1;
break;
}
}
}
//---------END---------------//
if (len == 0) {
x = 0;
}
return x;
}
public static int simple_match(String s, String t) {
int x = 0;
String tempt;
int len = s.length();
//----------Work Body----------//
for (int i = 1; i <= word_count(t); i++) {
tempt = split_string(t, i);
if (tempt.length() == s.length()) {
if (s.contains(tempt)) {
x = 1;
break;
}
}
}
//---------END---------------//
if (len == 0) {
x = 0;
}
return x;
}
public static int smart_match(String ts, String tt) {
char[] s = new char[ts.length()];
s = ts.toCharArray();
char[] t = new char[tt.length()];
t = tt.toCharArray();
int slen = s.length;
//number of 3 combinations per word//
int combs = (slen - 3) + 1;
//percentage per combination of 3 characters//
int ppc = 0;
if (slen >= 3) {
ppc = 100 / combs;
}
//initialising an integer to store the total % this class genrate//
int x = 0;
//declaring a temporary new source char array
char[] ns = new char[3];
//check if source char array has more then 3 characters//
if (slen < 3) {
} else {
for (int i = 0; i < combs; i++) {
for (int j = 0; j < 3; j++) {
ns[j] = s[j + i];
}
if (cross_full_match(ns, t) == 1) {
x = x + 1;
}
}
}
x = ppc * x;
return x;
}
/**
*
* #param s
* #param t
* #return
*/
public static int cross_full_match(char[] s, char[] t) {
int z = t.length - s.length;
int x = 0;
if (s.length > t.length) {
return x;
} else {
for (int i = 0; i <= z; i++) {
for (int j = 0; j <= (s.length - 1); j++) {
if (s[j] == t[j + i]) {
// x=1 if any charecer matches
x = 1;
} else {
// if x=0 mean an character do not matches and loop break out
x = 0;
break;
}
}
if (x == 1) {
break;
}
}
}
return x;
}
public static String split_string(String s, int n) {
int index;
String temp;
temp = s;
String temp2 = null;
int temp3 = 0;
for (int i = 0; i < n; i++) {
int strlen = temp.length();
index = temp.indexOf(" ");
if (index < 0) {
index = strlen;
}
temp2 = temp.substring(temp3, index);
temp = temp.substring(index, strlen);
temp = temp.trim();
}
return temp2;
}
public static int word_count(String s) {
int x = 1;
int c;
s = s.trim();
if (s.isEmpty()) {
x = 0;
} else {
if (s.contains(" ")) {
for (;;) {
x++;
c = s.indexOf(" ");
s = s.substring(c);
s = s.trim();
if (s.contains(" ")) {
} else {
break;
}
}
}
}
return x;
}
}
Just supply the two strings as argument to lock_match(string1, string2) and it will return the integer value of matching. If the size of string is bigger then increase the total name variable size
in the code.
Like int total=1000
Then the result will be given out of 0 to 1000.
This code is case sensitive.
Uppercase or lowercase both strings to get rid from this problem.
Source code available at: lock match
You can use Apache Commons Lang 3.
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang.version}</version>
</dependency>
#Test
public void test_stringDistance() throws Exception {
String teamName = "Partizn Belgrade";
String propositionName = "Partizan Belgrade";
// This one seems better
double distance = StringUtils.getJaroWinklerDistance(teamName, propositionName);
System.out.println(distance);
}
This is print out percentage, the larger the better (100% is exact )
org.apache.commons.lang3.StringUtils.getJaroWinklerDistance(first, second) is deprecated as of commons-lang3:3.6
Use new org.apache.commons.text.similarity.JaroWinklerDistance().apply(left, right) instead where left and right stand for first and second respectively. See maven dependency below
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>

java toString representation

I'm new to java and I'm trying to see if the method public String toString() is representing correctly the polynomial function. I don't know how to give the coefficients from main so that the class Func receives them.
package ro.utcluj.poo.lab04;
import java.util.Scanner;
class Func {
public double[] coef; //the coefficients
public int nrCoef; //coefficients number
public Func(double[] input)
{
nrCoef = input.length;
this.coef = new double[nrCoef];
for (int counter = 0; counter < input.length; counter++)
coef[counter] = input[counter];
}
public double getFuncValue(double x)
{
double exponent = nrCoef;
double y = 0;
double sum = 0;
for(int i = nrCoef; i >= 0; i--)
{
y = coef[i]*Math.pow(x, exponent-1); //n grade polynomial function
exponent--;
sum += y; //the sume for each member
}
return sum;
}
public double getDerivValue(double x)
{
double deriv = 0;
double rezDeriv = 0;
for(int i = 0; i < nrCoef - 1; i++)
{
deriv = coef[i]*(nrCoef - i)*Math.pow(x, nrCoef - i -1);
rezDeriv += deriv;
}
return rezDeriv;
}
public String toString()
{
String s = new String(" ");
int exp = nrCoef-1;
for(int i = 0; i < nrCoef; i++)
{
if(exp == 0 && coef[i] > 0)
s +="+" + coef[i];
else if(exp == 0 && coef[i] < 0)
s +=coef[i];
else if(exp == 1 && coef[i] > 0 && i == 0)
s +="+" + coef[i] + "x";
else if(exp == 1 && coef[i] >0)
s +="+" + coef[i];
else if(exp == 1 && coef[i] < 0)
s+=coef[i];
else if(coef[i] == 0)
s += "";
else if(coef[i] > 0 && i!=0)
s +="+" + coef[i]+"x^" + exp;
else
s +=coef[i] + "x^" + exp;
exp--;
System.out.println(s);
}
return s;
}
}
.
public class Main04 {
public static void main(String[] args) {
double[] v = new double[]{3,5,4};
Func f = new Func(v);
}
}
If you want to see what toString() does on your object f in main, all you need to do is
System.out.println(f);
f already has the coefficients that you passed into its constructor. println will call the object's toString() method and output the resulting string for you to see.
Also, as Steven pointed out in the comments, you don't need to put:
System.out.println(s);
in your toString() method itself. toString is supposed to produce and return the string. Your main method can deal with printing it out.
It's pretty simple to see what toString() does on object f in main...
You only have to yo use :
System.out.println(f);
This method will print the result of toString() to the command line.
That's all ;)
That worked but if I give the values {-3, -5, -4} I receive this:
-3.0x^2-5.0-4.0
It's missing the x from the second term(-5.0x). That is happining only if the second value is a negative one. For positive values it's working fine.
Try this way.
class Func {
public double[] coef; // the coefficients
public int nrCoef; // coefficients number
private StringBuilder sbl = new StringBuilder();
private StringBuilder tsbl = new StringBuilder();
public Func(double[] input) {
nrCoef = input.length;
this.coef = new double[nrCoef];
sbl.append("\nF(x) = ");
int exp = 0;
for (int counter = 0; counter < nrCoef; counter++) {
coef[counter] = input[counter];
if (coef[counter] != 0) {
if (counter != 0) {
sbl.append(coef[counter] < 0 ? " - " : " + ");
} else if (coef[counter] < 0) {
sbl.append(" - ");
}
exp = nrCoef - counter - 1;
sbl.append(Math.abs(coef[counter])+(exp == 0 ? "" : exp == 1 ? "*x" : "*x^"+exp));
}
}
}
public String toString() {
return tsbl.toString().isEmpty() ? sbl.toString() : tsbl.toString();
}
public double getFuncValue(double x) {
double sum = 0;
for (int index = 0; index < nrCoef; index++) {
sum += coef[index] * Math.pow(x, nrCoef - index - 1); // n grade polynomial
}
tsbl = new StringBuilder();
tsbl.append(sbl.toString());
tsbl.append("\nF(");
tsbl.append(x);
tsbl.append(") = "+sum);
return sum;
}
...

How to replace an integer element in a 2d array with a string type, using a Random

I have this table (2d array) and I'm using a Random utility from numbers 0-4 to select a row and column to replace a number with the letter "P" and I have everything but I get this.
- Type mismatch: cannot convert from String
to int
- Type mismatch: cannot convert from
Random to int
- Type mismatch: cannot convert from
Random to int
Meanwhile this question How to change value of array element in 2D arrays? says you can just do
someArray[row][column] = "x";
Here is what I have (I assume my problem is with using the random)
import java.util.Random;
public class Server{
private int number;
private boolean pennyLanded;
public Server()
{
int n = 0;
number = n;
pennyLanded = false;
}
public boolean pennyLanded()
{
return pennyLanded;
}
public void setPennyLanded()
{
pennyLanded = true;
}
public int getNumber()
{
return number;
}
public String toString()
{
if (pennyLanded)
return "P";
else
return "" + number;
}
public static int[][] tableMaker(){
int[][] table = new int[5][5];
for(int i=0; i<table.length; i++){
for(int j=0; j<table.length; j++){
if(i==2 && j==2){
table[i][j] =3;
}
else if(i==0 || i==4){
table[i][j] = 1;
}
else if(j==4 || j==0){
table[i][j] = 1;
}
else if((i==1 || i==3) && (j>0 || j<4)){
table[i][j] = 2;
}
else if((i==2 && j==1) || (i==2 && j==3)){
table[i][j] = 2;
}
}
}
for(int i=0; i<table.length; i++){
for(int j=0; j<table.length; j++){
System.out.print(table[i][j] + " ");
}
System.out.println();
}
return table;
}
public static int[][] tossPenny(){
Random row = new Random();
Random column = new Random();
int[][] table = Server.tableMaker();
for(int i=0; i<5; i++){
table[row.nextInt(4)][column.nextInt(4)] = -1;
}
return table;
}
}
The table is printed in a Client class
public class Client{
public static void main(String[] args){
System.out.println(Server.tableMaker());
}
}
I Don't know how simple of a fix this is, and I have searched I just have a particular problem
The table is printed as so
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
And I would like something like this say the random puts out 1 and 2
1 1 1 1 1
1 2 P 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
You have to use row.nextInt(int max) instead of row, where the generated random integer n is 0 <= n < max. The parameter of new Random() only defines a seed, so I suggest you not use a constant number there unless you want your random algorithm to be deterministic.
Furthermore you mixes up the types a bit. tableMaker() should be String[][] in order to write Strings into it and tossPenny() should be void since it doesn't return anything.
import java.util.Random;
public class Server {
public static String[][] tableMaker() {
String[][] table = new String[5][5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
if (i == 2 && j == 2) {
table[i][j] = "" + 3; // Converting int 3 to String "3"
} else if (i == 0 || i == 4) {
table[i][j] = "" + 1;
} else if (j == 4 || j == 0) {
table[i][j] = "" + 1;
} else if ((i == 1 || i == 3) && (j > 0 || j < 4)) {
table[i][j] = "" + 2;
} else if ((i == 2 && j == 1) || (i == 2 && j == 3)) {
table[i][j] = "" + 2;
}
}
}
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
return table;
}
public static void tossPenny(int a) {
Random row = new Random();
Random column = new Random();
String Penny = "P";
String[][] table = Server.tableMaker();
for (int i = 0; i < 5; i++) {
table[row.nextInt(5)][column.nextInt(5)] = Penny;
}
}
}
Was able to figure it out with help of a IRL friend and this avoids the memory store errors as seen before, Server is below
import java.util.Random;
public class Server{
private static int[][] table;
public static int[][] tableMaker(){
table = new int[5][5];
for(int i=0; i<table.length; i++){
for(int j=0; j<table.length; j++){
if(i==2 && j==2){
table[i][j] =3;
}
else if(i==0 || i==4){
table[i][j] = 1;
}
else if(j==4 || j==0){
table[i][j] = 1;
}
else if((i==1 || i==3) && (j>0 || j<4)){
table[i][j] = 2;
}
else if((i==2 && j==1) || (i==2 && j==3)){
table[i][j] = 2;
}
}
}
return table;
}
public static void printTable(){
for(int i=0; i<table.length; i++){
for(int j=0; j<table.length; j++){
if(table[i][j] == -1) System.out.print("P ");
else System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
public static int[][] tossPenny(){
Random row = new Random();
Random column = new Random();
for(int i=0; i<5; i++){
table[row.nextInt(4)][column.nextInt(4)] = -1;
}
return table;
}
}
Client is here
import java.util.Scanner;
public class Client{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Server.tableMaker();
Server.printTable();
System.out.println();
Server.tossPenny();
Server.printTable();
input.close();
}
}
Thanks a lot everyone especially #DavidWallace You helped me get around most of my problems and I was able to fix everything using the private static int[][] table;

Categories