I got this assignment in Java and I don't have a single clue on how to do it.
The task is to receive an integer n > 0, and to print n number of frames constructed by * inside each other, while the inner frame will have the letter "X" constructed by 4n+1 *.
I can't use arrays or strings.
For example:
n=1 will print:
*******
* *
* * * *
* * *
* * * *
* *
*******
n=2 will print:
*************
* *
* ********* *
* * * *
* * * * * *
* * * * * *
* * * * *
* * * * * *
* * * * * *
* * * *
* ********* *
* *
*************
This is what I have so far:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int size = n * 6 + 1;
int x = 1;
int y = 1;
for (int i = 0; i < n; i = i + 1) {
for (int i3 = 0; i3 < size; i3 = i3 + 1) {
System.out.print("*");
}
System.out.println("");
y = y + 1;
for (int i1 = 0; i1 < size - 2; i1 = i1 + 1) {
System.out.print("*");
for (int i2 = 0; i2 < size - 2; i2 = i2 + 1) {
System.out.print(" ");
}
System.out.println("*");
y = y + 1;
}
for (int i4 = 0; i4 < size; i4 = i4 + 1) {
System.out.print("*");
}
}
There are many different approaches to this problem. This may not be the best, but it's quite simple and educational IMO.
The main idea is: you don't need to know how to print the entire frame. You only need to know how to print 1/4 of it - then repeat it in reverse X order, then repeat it in reverse Y order. Let's start with drawing X, specifically - one diagonal of it. If the "X" has to have 4n+1 *, it has 4 arms with a stars each and one * in the middle - totaling to 4 * a + 1 stars - so, obviously, 4n+1 == 4a+1, and each arm has to have exactly n *'s. Let's use XY Cartesian coordinate system. Thus, we only have an asterisk if x == y - otherwise we have s space there.
for ( int y = 0; y < n; y++ ) {
for ( int x = 0; x < n; x++ ) {
System.out.print( ( x == y ) ? '*' : ' ' );
}
System.out.println();
}
Now, let's add a mirror copy to it by iterating in reverse too:
for ( int y = 0; y < n; y++ ) {
for ( int x = 0; x < n; x++ ) {
System.out.print( ( x == y ) ? '*' : ' ' );
}
for ( int x = n; x >= 0; x-- ) {
System.out.print( ( x == y ) ? '*' : ' ' );
}
System.out.println();
}
Now, let's try to get into valid Cartesian:
int x, y;
for ( y = -n; y <= n; y++ ) {
for ( x = -n; x < 0; x++ ) {
System.out.print( ( x == y || x == -y ) ? '*' : ' ' );
}
for ( ; x <= n; x++ ) {
System.out.print( ( x == y || x == -y ) ? '*' : ' ' );
}
System.out.println();
}
and, finally, we can figure that it's just
for ( int y = -n; y <= n; y++ ) {
for ( int x = -n; x <= n; x++ ) {
System.out.print( hasAsterisk( Math.abs(x), Math.abs(y) ) ? '*' : ' ' );
}
System.out.println();
}
with, for example
static boolean hasAsterisk( int x, int y ) {
return x == y;
}
Extend this code to handle the frames, and you're set. Each "quart part" of the frame is only * for each n, 2n chars total - the cross itself is n in length (see above) plus 1 central asterisk; to sum up, X and Y will range over int [-3n,3n] - call that 3n some m and use it as the range for iteration.
As an additional hint, the formula is different for the inner cross (i.e. abs(x)<n,abs(y)<n), and different for the frames themselves. The formula for the frames can be easily figured out if you notice that it's every second row, in the shape of two asterisk triangles in axis X added to two triangles in axis Y.
return ( x <= n && y <= n ) ? x == y : ( ( x < y ) ? y % 2 == nMod2 : x % 2 == nMod2 );
Related
Given a square matrix of size N*N, where each cell is associated with a specific cost. A path is defined as a specific sequence of cells which starts from top left cell move only right or down and ends on bottom right cell. We want to find the path with maximum value. Now to make things even more interesting: you also have T tokens. You can use the tokens to double the value on the current square. You can only use one token on any given square.
This is how I have solved the first part of the problem.
public static long pathWithMaxCost(int[][] n, int tokens) {
int[][] arr = new int[n.length][n[0].length];
// starting position
arr[arr.length - 1][0] = n[arr.length - 1][0];
// first column
for (int i = arr.length - 2; i >= 0; i--) {
arr[i][0] = arr[i + 1][0] + n[i][0];
}
// last row
for (int i = 1; i < arr[0].length; i++) {
arr[arr.length - 1][i] = arr[arr.length - 1][i - 1] + n[arr.length - 1][i];
}
for (int i = arr.length - 2; i >= 0; i--) {
for (int j = 1; j < arr[0].length; j++) {
arr[i][j] = Math.max(arr[i][j - 1], arr[i + 1][j]) + n[i][j];
}
}
return arr[0][arr[0].length - 1];
}
Now how can I handle the token part, T square values can be doubled?
static long pathWithMaxCostHash(int[][] n, int x, int y, int tokkens) {
if (x < 0 || x >= n.length || y < 0 || y >= n[0].length)
return -1;
String key = x + ":" + y + ":" + tokkens;
if (map.containsKey(key))
return map.get(key);
if(x==n.length-1&&y==0) {
if (tokkens > 0 && n[x][y] > 0) {
map.put(key,(long)n[n.length-1][0]*2);
return 2*n[n.length-1][0];
}
map.put(key,(long)n[n.length-1][0]);
return n[n.length-1][0];
}
//without picking double
long val = n[x][y]
+ Math.max(pathWithMaxCostHash(n, x + 1, y, tokkens), pathWithMaxCostHash(n, x, y - 1, tokkens));
//with picking double
if (tokkens > 0 && n[x][y] > 0) {
long val2 = 2 * n[x][y] + Math.max(pathWithMaxCostHash(n, x + 1, y, tokkens - 1),
pathWithMaxCostHash(n, x, y - 1, tokkens - 1));
val2 = Math.max(val, val2);
map.put(key, val2);
return val2;
}
map.put(key, val);
return val;
}
I'll give you a recursive approach, guess you can figure out dynamic programming based solution with this.
Initialize your dp 2d array with 0's
function: pathWithMaxCost(int x,int y,int tokens, int arr[][],int dp[][])
if(dp[x][y]) return dp[x][y];
few boundary conditions here...
return dp[x][y]=max(arr[x][y]+pathWithMaxCost(x,y+1,tokens,arr), arr[x][y]+pathWithMaxCost(x+1,y,tokens,arr), (arr[x][y]*2)+pathWithMaxCost(x,y+1,tokens-1,arr), (arr[x][y]*2)+pathWithMaxCost(x+1,y,tokens-1,arr))
Add another dimension for T, so the general check for a cell would be:
m[y][x][t] = max(
2 * n[y][x] + m[y-1][x][t-1],
2 * n[y][x] + m[y][x-1][t-1],
n[y][x] + m[y-1][x][t],
n[y][x] + m[y][x-1][t]
)
for all y,x,t
Let's consider the edge cases:
// first element
if x + y == 0:
m[y][x][0] = n[y][x]
m[y][x][1] = 2 * n[y][x]
m[y][x][t] = -Infinity, for t > 1
// first row
if y == 0:
m[y][x][t] = max(
2 * n[y][x] + m[y][x-1][t-1],
n[y][x] + m[y][x-1][t]
)
// first column
if x == 0:
m[y][x][t] = max(
2 * n[y][x] + m[y-1][x][t-1],
n[y][x] + m[y-1][x][t]
)
I have to do this 2d DCT of an image for my project.
I translated the formula right to code. It all seems fine logically but it doesn't give the required result. I've tallied it with matlab function to check the results for a 3x3 matrix but they are incorrect.
Also, what and how I've coded gives a huge number of loops such that an actual image operation takes hours to compute.
Any suggestion to reduce the loops and pointing of program error would be great.
Thanks.
This is my code.
double alpha_p, alpha_q;
double pi = Math.atan(1.0) * 4.0;
//dct begins
System.out.println("it begins");
for (int p = 0; p < M; p++) {
for (int q = 0; q < N; q++) {
if (p == 0)
alpha_p = 1 / sqrt(M);
else
alpha_p = sqrt(2 / M);
if (q == 0)
alpha_q = 1 / sqrt(N);
else
alpha_q = sqrt(2 / N);
double toreturn = 0;
for (int m = 0; m < M; m++) {
for (int n = 0; n < N; n++) {
toreturn = toreturn + img[m][n]
* cos(((2 * m + 1) * p * pi) / 2 * M)
* cos(((2 * n + 1) * q * pi) / 2 * N);
}
}
dctimg[p][q] = alpha_p * alpha_q * toreturn;
System.out.println("euta");
}
}
// dct over
System.out.println("its over");
//inverse dct begins
for (int m = 0; m < M; m++) {
for (int n = 0; n < N; n++) {
double toreturn = 0;
for (int p = 0; p < M; p++) {
for (int q = 0; q < N; q++) {
if (p == 0)
alpha_p = 1 / sqrt(M);
else
alpha_p = sqrt(2 / M);
if (q == 0)
alpha_q = 1 / sqrt(N);
else
alpha_q = sqrt(2 / N);
toreturn = toreturn + alpha_p * alpha_q * dctimg[p][q]
* cos(((2 * m + 1) * p * pi) / 2 * M)
* cos(((2 * n + 1) * q * pi) / 2 * N);
}
}
finalimg[m][n] = toreturn;
}
}
//inverse dct over
First of all, in the formula of DCT the denominator of cos is 2 * M. It is a typical mistake. 4 / 2 * 2 = 4 not 1
cos(((2 * m + 1) * p * pi) / 2 * M) should be cos(((2 * m + 1) * p * pi) / (2 * M))
Parentheses are required in all four cases.
Another moment that I want to mention is sqrt(2 / M). If M has an integer type (it is not clear by your code) and it is greater than 2, then the expression 2 / M is equal to 0. Because both operands have integer types and / gives only integer part. To fix it, add a floating point like that sqrt(2.0 / M).
As you have already noticed, there is a lot of loops, in other words, the complexity of the 2D DCT II is O(n^4).
In real life nobody applies DCT to the whole actual image. The image is split into blocks of size 8x8 and each block is processed by DCT. This approach allows to keep n low and the complexity becomes acceptable.
To decrease the algorithmic complexity, I want to link here, where methods of using 1D DCT and FFT are good explained.
I have seen several questions about the Tortoise and Hare Race but they are all pertaining to applets and I am not programming an applet. The program is meant to I am having some trouble with the display output of my program. I would like to have the program display an output that looks something like this:
______T__________H________________________________
__________T_______________________H_______________
_____________T________H___________________________
etc. until either the tortoise or the hare reaches the end and wins the race. As of right now, my output looks like this:
______________________________HT__________________________________________________HT__________________________________________________HT_
over and over in what seems to be an infinite loop. Here is my code:
public class TortoiseAndHair {
public static void main ( String [] args )
{
int t = 0; // Keeps track of tortoise progress
int h = 0; // Keeps track of hare progress
System.out.println( "AND THEY'RE OFF!!" );
while (t < 50 || h < 50)
{
hareMove( h );
tortoiseMove( t );
if (t>1 && h> 1 && t == h) // Display when tortoise and hare occupy same space beyond start
{
System.out.print( "OUCH!!");
}
if ( t < 1 )
{ // Prevents tortoise from slipping behind start
t = 1;
}
if ( h < 1 )
{ // Prevents hare from slipping behind start
h = 1;
}
if ( t > 50 )
{ // Prevents tortoise from going passed finish line
t = 50;
}
if ( h > 50 )
{ // Prevents hare from going passed finish line
h = 50;
}
for ( int count = 1; count <= 50; count++)
{
System.out.print( "_" );
if ( count == h )
{
System.out.print( "H" );
}
if ( count == t )
{
System.out.print( "T" );
}
}
if (h < 50 && t == 50)
{ //Output if tortoise wins
System.out.print( "TORTOISE WINS!!" );
}
if ( t < 50 && h == 50)
{ // Output if hare wins
System.out.print( "HARE WINS!!" );
}
if ( h == 50 && t == 50)
{
System.out.print( "IT'S A TIE!!" );
}
}
}
/**
* This method will calculate the random integer that will dictate the tortoise's movements on the board,
* use that random integer to determine the tortoise's movements (tMove), and add that to the counter keeping track
* of the tortoise's position
* #param t is an int variable that is keeping track of the tortoises position on the board
* #return the tortoise's current position on the board after that turn
* Pre-Conditions: n is an int between 1 and 10, t is a positive int greater than 0 and less than 50
*/
public static int tortoiseMove (int t)
{
int n;
int tMove = 0;
n = (int) ( 10 * Math.random() ) + 1; // Generates random number between 1 and 10
if ( n > 10 )
{ // ensures n doesn't go higher than 10
n = 10;
}
// Series of if/else statements to control tMove
if ( n >= 1 && n <= 5)
{ // Fast plod if n is between 1 and 5
tMove = 3;
}
else
{
if ( n >= 6 && n <= 8)
{ // Slow Plod if n is between 6 and 8
tMove = 1;
}
else
{
if ( n == 9 || n == 10 )
{ // Slip if n is 9 or 10
tMove = -6;
}
}
}
// Add determined movement to tortoise counter and return that value
t += tMove;
return t;
}
/**
* This method will calculate the random integer that will dictate the hare's movements on the board,
* use that random integer to determine the hare's movements (hMove), and add that to the counter keeping track
* of the hare's position on the board
* #param h is an int variable keeping track of the hare's current position on the board
* #return the hare's position on the board after current turn
* Pre-Condition: n is an int between 1 and 10, h is a positive int greater than 0 and less than 50
*/
public static int hareMove (int h)
{
int n;
int hMove = 0;
n = (int) ( 10 * Math.random() ) + 1; // Generates random number between 1 and 10
if ( n > 10 )
{ // ensures n doesn't go higher than 10
n = 10;
}
//Series of if/else statements to control hMove
if ( n == 1 || n == 2 )
{ // Big hop if n is 1 or 2
hMove = 9;
}
else
{
if ( n >= 3 && n <= 5)
{ // Small hop is n is between 3 and 5
hMove = 1;
}
else
{
if ( n == 6 )
{ // Big slip is n is 6
hMove = -12;
}
else
{
if ( n == 7 || n == 8 )
{ // Small slip if n is 7 or 8
hMove = -2;
}
else
{
if ( n == 9 || n == 10 )
{ // Hare falls asleep if n is 9 or 10
hMove = 0;
}
}
}
}
}
// Add determined movement to hare counter and return value of h
h += hMove;
return h;
}
}
You never reassign h and t after moving
h = hareMove( h );
t = tortoiseMove( t );
Primitives are passed by value, so whatever change you made to h and t in the move method are not reflected in the original values.
Now I have completed the finding 23 sets of x y z values satisfy the condition x^3+y^3=1+z^3 & x
int setsFound = 0;
System.out.println("The first 23 sets ordered by increasing x.");
for (long x = 1; setsFound < 23; x++) {
for (long z = x + 1; z<x*x; z++) {
long y = (long) Math.pow((1 + z*z*z - x*x*x), 1f/3f);
if (x * x * x == 1 + z * z * z - y * y *y && x<y && y<z) {
setsFound++;
System.out.println("X: " + x + ", Y: " + y + ", Z: " + z);
}
}
}
But the code I have is very inefficient, can anyone help me to fix this please?
Here is a working code:
int setsFound = 0;
System.out.println("The first 23 sets ordered by increasing x.");
for (long z = 1; setsFound < 23; z++) {
for (long y = z - 1; y > 0; y--) {
long x = (long) Math.pow((1 + z * z * z - y * y * y), 1f/3f);
if(y <= x) break;
if (x * x * x == 1 + z * z * z - y * y *y) {
setsFound++;
System.out.println("X: " + x + ", Y: " + y + ", Z: " + z);
}
}
}
Couple of problems in the old one:
1/3 == 0 (because it's integer division) //use 1f/3f
x and z are swapped - you want z > x, not the other way around
(long)Math.pow(4*4*4, 1.0/3) == (long)3.9999999999999996 == 3 // use round
If you start the other way, with X < Y < Z by incrementing Y and Z up to a limit, you can gain some efficiencies. Once Z^3 > X^3 + Y^3 + 1, you can skip to the next Y value due to the concavity of the cubic function.
This implementation in C# works pretty fast on a laptop:
UInt64 setsFound = 0;
UInt64 xlim = 10000;
UInt64 ylim = 1000000;
UInt64 zlim = 10000000;
//int ctr = 0;
Console.WriteLine("The first 23 sets ordered by increasing x.");
Parallel.For(1, (long)xlim, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
//for (UInt64 i = 0; i < xlim; i++)
{
UInt64 x = (UInt64)i;
UInt64 xCu = x * x * x;
int zFails = 0;
for (UInt64 y = x + 1; y < ylim; y++)
{
UInt64 yCu = y * y * y;
zFails = 0;
for (UInt64 z = y + 1; z < zlim & zFails < 1; z++)
{
UInt64 zCu = z * z * z;
if (xCu + yCu - zCu == 1)
{
Console.WriteLine(String.Format("{0}: {1}^3 + {2}^3 - {3}^3 = 1", setsFound, x, y, z));
setsFound++;
}
else if (zCu > xCu + yCu - 1)
{
zFails++;
}
}
}
}
);
Obviously you can take out the parallelization. Also, here are the first 19 elements in that set (computer is still running, I'll try to post the last 4 later):
output http://desmond.yfrog.com/Himg640/scaled.php?tn=0&server=640&filename=8qzi.png&xsize=640&ysize=640
Since some weeks ago I have been trying to convert this c and other c function to java language (i'm a newbie on it).
My first problem is how-to convert to java code, the pointers on lines like:
q = fdata + ind;
datend = fdata + buff_size;
For example when "ind" has a negative position (-220 for example) the pointer will be on "ind" position before "fdata" values, also the same occur with datend var.
I figured out that can be solved on isolated way by creating an index var for each pointer to know where there are pointing at. The real problem for me comes a few line after that, when i trying to not run over end of frame of "fdata" array.
Can some body with more experiences help me please?
Thank.
static Stat *stat = NULL;
static float *mem = NULL;
static Stat*
get_stationarity(fdata, freq, buff_size, nframes, frame_step, first_time)
float *fdata;
double freq;
int buff_size, nframes, frame_step, first_time;
{
static int nframes_old = 0, memsize;
float preemp = 0.4f, stab = 30.0f;
float *p, *q, *r, *datend;
int ind, i, j, m, size, order, agap, w_type = 3;
agap = (int) (STAT_AINT * freq);
size = (int) (STAT_WSIZE * freq);
ind = (agap - size) / 2;
if (nframes_old < nframes || !stat || first_time) {
/* move this to init_dp_f0() later */
nframes_old = nframes;
if (stat) {
ckfree((char *) stat->stat);
ckfree((char *) stat->rms);
ckfree((char *) stat->rms_ratio);
ckfree((char *) stat);
}
if (mem) ckfree((void *) mem);
stat = (Stat *) ckalloc(sizeof (Stat));
stat->stat = (float*) ckalloc(sizeof (float) *nframes);
stat->rms = (float*) ckalloc(sizeof (float) *nframes);
stat->rms_ratio = (float*) ckalloc(sizeof (float) *nframes);
memsize = (int) (STAT_WSIZE * freq) + (int) (STAT_AINT * freq);
mem = (float *) ckalloc(sizeof (float) * memsize);
for (j = 0; j < memsize; j++) mem[j] = 0;
}
if (nframes == 0) return (stat);
q = fdata + ind;
datend = fdata + buff_size;
if ((order = (int) (2.0 + (freq / 1000.0))) > BIGSORD) {
fprintf(stderr,
"exceeds that allowable (%d); reduce Fs\n", BIGSORD);
order = BIGSORD;
}
/* prepare for the first frame */
for (j = memsize / 2, i = 0; j < memsize; j++, i++) mem[j] = fdata[i];
/* do not run over end of frame */
for (j = 0, p = q - agap; j < nframes; j++, p += frame_step, q += frame_step) {
if ((p >= fdata) && (q >= fdata) && (q + size <= datend))
stat->stat[j] = get_similarity(order, size, p, q,
&(stat->rms[j]),
&(stat->rms_ratio[j]), preemp,
stab, w_type, 0);
else {
if (first_time) {
if ((p < fdata) && (q >= fdata) && (q + size <= datend))
stat->stat[j] = get_similarity(order, size, NULL, q,
&(stat->rms[j]),
&(stat->rms_ratio[j]),
preemp, stab, w_type, 1);
else {
stat->rms[j] = 0.0;
stat->stat[j] = 0.01f * 0.2f; /* a big transition */
stat->rms_ratio[j] = 1.0; /* no amplitude change */
}
} else {
if ((p < fdata) && (q + size <= datend)) {
stat->stat[j] = get_similarity(order, size, mem,
mem + (memsize / 2) + ind,
&(stat->rms[j]),
&(stat->rms_ratio[j]),
preemp, stab, w_type, 0);
/* prepare for the next frame_step if needed */
if (p + frame_step < fdata) {
for (m = 0; m < (memsize - frame_step); m++)
mem[m] = mem[m + frame_step];
r = q + size;
for (m = 0; m < frame_step; m++)
mem[memsize - frame_step + m] = *r++;
}
}
}
}
}
/* last frame, prepare for next call */
for (j = (memsize / 2) - 1, p = fdata + (nframes * frame_step) - 1; j >= 0 && p >= fdata; j--)
mem[j] = *p--;
return (stat);
}
This code is easier rewritten than ported. The reason is, that it uses a large number of pointer-arithmetic and casting.
It looks to me like this code combines a sliding window and averaging functions over the data. You can easily do this in Java, just place each time-series in an array, use an index (instead of a pointer) to point at the array's entries. In the case where the C-code uses a pointer and then a (possibly negative) offset as a second pointer just use two indices into the time-series-array.
It is easier to do this if you have the formula (math-notation. sliding-window plus averaging functions) that this code is supposed to compute and translate the formula to java.