Using logical operations inside a for loop header - for-loop

sIn the following code:
for( ( i = j = 0 ); ( i < 3 ) && ( j < 3 ); ( i ++ ) & ( j ++ ) )
{
/* Some code */
}
OR
for( ( i = 0 ) & ( j = 0 ); ( i < 3 ) && ( j < 3 ); ( i ++ ) & ( j ++ ) )
{
/* Some code */
}
When running the code, a warning message appears saying: value computed is not used. Why is that ? Providing that the code isn't functioning well due to the logical errors!
Please help ..

Is this something that you want :
for( i = 0,j = 0 ; i < 3 && j<3; i++ , j++ )
{
/* your code */
}
This should work fine in case you want to use two variables in one for loop.
This way both i and j will be initialized to 0 and both with get incremented by 1 and the less than condition will check for the limit for both variables
In case, you want to loop through two arrays you can do something like this :
int[] arr1 = new int[]{1,2,3,4,5};
int[] arr2= new int[]{6,7,8,9,0,11};
for( i = 0,j = 0 ; i< arr1.length && j<arr2.length; i++ , j++ )
{
System.out.println(arr1[i] + " " +arr2[j]);
}

Related

Calculate and list how many different 4 digit numbers can be done with the numbers 0 to 9?

There is something I want to learn.
Let's say we have some single digit numbers.
Example: 1-2-3-4-5-6-7-8-9-0
Example II: 1-2-4-6-0
And with these numbers, we want to get 4-digit numbers that are different from each other.
And we want to print them as lists.
Result:
4676
4236
1247
1236
....
Is it possible to do this?
You can write and run a macro like this:
// retrieve the selected text
str = document.selection.Text;
// check the input string format. The input must be something like: "1-2-4-6-0"
if( str.length == 0 ) {
alert( "Select the input string" );
Quit();
}
for( i = 0; i < str.length; ++i ) {
c = str.substr( i, 1 );
if( i % 2 == 0 ) {
if( c < '0' || c > '9' ) {
alert( "not digit" );
Quit();
}
}
else {
if( c != '-' ) {
alert( "not separated by '-'" );
Quit();
}
}
}
var arr = new Array();
j = 0;
for( i = 0; i < str.length; ++i ) {
if( i % 2 == 0 ) {
c = str.substr( i, 1 );
arr[j++] = c;
}
}
if( arr.length < 4 ) {
alert( "Input string should contain at least 4 digits" );
Quit();
}
// list all 4-digit combinations
len = arr.length;
str = "";
for( i = 0; i < len; ++i ) {
for( j = 0; j < len; ++j ) {
for( k = 0; k < len; ++k ) {
for( l = 0; l < len; ++l ) {
str += arr[i] + arr[j] + arr[k] + arr[l] + "\r\n";
}
}
}
}
// write the list in a new document
editor.EnableTab = true;
editor.NewFile();
document.write( str );
To run this, save this code as, for instance, GenCombinations.jsee, and then select this file from Select... in the Macros menu. Finally, select Run GenCombinations.jsee in the Macros menu after selecting an input string.

Bulk-sorted list vs priority queue performance in Java 8

I'm implementing a sweep-line algorithm in Java 8, in which I traverse a collection of objects sorted by a numeric key (e.g., the "xlo" coordinate of a rectangle). Currently, I'm implementing this using a PriorityQueue<item>( key-extractor ). I realize, though, that I'm not really using the full functionality of the PriorityQueue (ability to intersperse add's, delete's and peek's/poll's), but only adding the items at the start of execution, then proceeding to peek/poll them later (no further insertions or deletions). As such, I'm thinking of replacing the PriorityQueue with a simple Queue<item>, fill it up, sort it, and then peek/poll the items from the front.
I'm going to try modifying my code along these lines, but before I do, I'm wondering how much I might expect to save by the substitution. Formally, it seems like the complexity of the two approaches are equivalent, but I'm suspecting there's a significant different in the constant. Suggestions?
Thanks, #pjs, for the suggestion. I used a simple class Number to force
the sorting to use an accessor method as my application does. Here are the results for 1000 trials
of adding/sorting/retrieving various numbers of Numbers using a
PriorityQueue<Number>, an ArrayList<Number> (with explicit sort) and an
array of Numbers (with explicit sort); numbers are in seconds:
For 1000 trials PriorityQueue ArrayList Array
n=100 0.021 0.024 0.033
n=1000 0.220 0.203 0.205
n=10000 3.157 2.772 2.751
So, the answer is "it depends". For a small number of Numbers in the collection, PriorityQueue is the winner. For larger numbers, array is the winner.
Here is the code I used; note that I repeated all the trials twice, to allow the JIT to work its magic, and reported times from the second repetition.
public class Benchmark {
static private final int n = 10000; // Number of Numbers
static private final int r = 1000; // Number of repetitions
static private Random rand = new Random();
static private class Number {
private int i;
public Number( int i ) { this.i = i; }
public int getNumber() { return i; }
}
static private PriorityQueue< Number >
sortedNumbersPQ = new PriorityQueue< Number >( Comparator.comparing( Number::getNumber ) );
static private List< Number > sortedNumbersAL = new ArrayList<>();
static private Number[] sortedNumbersAR = new Number[ n ];
static private int usePriorityQueue( int[] numbers ) {
int sum = 0;
for ( int i = 0; i < numbers.length; i++ )
sortedNumbersPQ.add( new Number( numbers[ i ] ) );
while ( ! sortedNumbersPQ.isEmpty() )
sum += sortedNumbersPQ.poll().getNumber();
return sum;
}
static private int useArrayList( int[] numbers ) {
int sum = 0;
sortedNumbersAL.clear();
for ( int i = 0; i < numbers.length; i++ )
sortedNumbersAL.add( new Number( numbers[ i ] ) );
Collections.sort( sortedNumbersAL, Comparator.comparing( Number::getNumber ) );
for ( int i = 0; i < numbers.length; i++ )
sum += sortedNumbersAL.get( i ).getNumber();
return sum;
}
static private int useArray( int[] numbers ) {
int sum = 0;
for ( int i = 0; i < numbers.length; i++ )
sortedNumbersAR[ i ] = new Number( numbers[ i ] );
Arrays.sort( sortedNumbersAR, 0, numbers.length, Comparator.comparing( Number::getNumber ) );
for ( int i = 0; i < numbers.length; i++ )
sum += sortedNumbersAL.get( i ).getNumber();
return sum;
}
static public void main( String args[] ) {
int[] numbers = new int[ n ];
for ( int i = 0; i < n; i++ )
numbers[ i ] = rand.nextInt( 1000000 );
long start = System.currentTimeMillis();
for ( int i = 0; i < r; i++ )
usePriorityQueue( numbers );
System.err.println( "Using PriorityQueue for " + r + " repeats of " + n + " items: " +
0.001 * ( System.currentTimeMillis() - start ) );
start = System.currentTimeMillis();
for ( int i = 0; i < r; i++ )
useArrayList( numbers );
System.err.println( "Using ArrayList for " + r + " repeats of " + n + " items: " +
0.001 * ( System.currentTimeMillis() - start ) );
start = System.currentTimeMillis();
for ( int i = 0; i < r; i++ )
useArray( numbers );
System.err.println( "Using Array for " + r + " repeats of " + n + " items: " +
0.001 * ( System.currentTimeMillis() - start ) );
start = System.currentTimeMillis();
for ( int i = 0; i < r; i++ )
usePriorityQueue( numbers );
System.err.println( "Using PriorityQueue for " + r + " repeats of " + n + " items: " +
0.001 * ( System.currentTimeMillis() - start ) );
start = System.currentTimeMillis();
for ( int i = 0; i < r; i++ )
useArrayList( numbers );
System.err.println( "Using ArrayList for " + r + " repeats of " + n + " items: " +
0.001 * ( System.currentTimeMillis() - start ) );
start = System.currentTimeMillis();
for ( int i = 0; i < r; i++ )
useArray( numbers );
System.err.println( "Using Array for " + r + " repeats of " + n + " items: " +
0.001 * ( System.currentTimeMillis() - start ) );
}
}

How do I keep track of path in TSP?

I found a simple solution to a TSP problem using bitmask here.
int n, src;
vector< vector< int > > graph, dp;
// initial status
void init() {
for ( int i = 0; i < n; ++i )
dp[ 1 << i ][ i ] = graph[ src ][ i ];
}
// TSP recursive
int TSP( int status, int x ) {
if ( dp[ status ][ x ] != -1 )
return dp[ status ][ x ];
int mask = 1 << x;
dp[ status ][ x ] = 1e9;
for ( int i = 0; i < n; ++i )
if ( i != x && ( status & ( 1 << i ) ) )
dp[ status ][ x ] = min( dp[ status ][ x ], TSP( status - mask, i ) + graph[ i ][ x ] );
return dp[ status ][ x ];
}
int main() {
scanf( "%d %d", &n, &src );
graph = vector< vector< int > >( n, vector< int >( n ) );
dp = vector< vector< int > >( 1 << n, vector< int >( n, -1 ) );
for ( int i = 0; i < n; ++i )
for ( int j = 0; j < n; ++j ) {
int x;
scanf( "%d", &x );
graph[ i ][ j ] = x;
}
init();
printf( "%d\n", TSP( ( 1 << n ) - 1, src ) );
return 0;
}
What if I want to know the path of the solution. How do I implement that?
What's come in my mind is to add a variable track[status][list of path]. But, I don't think it's a good solution. What is the best way to keep track of the path?

solving order of time in data structures

I want the order time(theta) for these algorithms. Can you help me please?
1)
For ( i = 1 ; i <= n ; i++ )
{
For( j=1 ; j<=n ; j++ )
X++;
n--;
}
2)
For ( i = 1 ; i<=n ; i = i*2)
For( j= 1 ; j <=n ; j = j*2 )
For(k=1 ; k<=j ; K++)
X++;
3)
For ( i=5 ; i<n-10 ; i++ )
For ( j=i ; j>1 ; j-- )
For ( k=1 ; k<j ; k++ )
{
S=S+k+j;
S=S*2;
}
They answer for the above question is:
1) theta(n^2)
2)theta(nlgn)
3)theta(n^3)

I'm programming sorting algorithm - Shellsort. Where is bug?

I'm programming sorting algorithm — Shellsort. Where is bug?
int shellsort( int ai_numbers[], const int ci_count ){
int i, j, temp, counter = 0, inc;
inc = ci_count / 2;
while ( inc > 0 )
{
for ( i = inc + 1; i < ci_count ; i++)
{
temp = ai_numbers[i];
j = i;
while ( j > inc && ai_numbers[j - inc] > temp )
{
ai_numbers[j] = ai_numbers[j - inc];
j = j - inc;
counter++;
}
ai_numbers[j] = temp;
}
inc = (int) (inc / 2.2);
}
return counter;
}
The condition in the inner loop,
while ( j > inc && ai_numbers[j - inc] > temp )
causes the algorithm to never even look at ai_numbers[0]. The algorithm seems to be written with 1-based array indices in mind.
The loop controls should be
for ( i = inc; i < ci_count ; i++)
and
while ( j >= inc && ai_numbers[j - inc] > temp )
to properly incorporate ai_numbers[0].

Resources