First, this is a homework assignment. I am supposed to create a program using a switch command. It asks the user to input 3 integers, then input an integer of 1-5 for the five cases average, max, min, total, and exit. I have pretty much completed this program, first having a user input 3 integers, then creating the switch "menu" structure, and inside each case, I attempted to create the mathematics for each of the arithmetic functions.
My error message is "cannot find symbol", which is a broad and vague error message to post about. Everything I have Googled, or found on this site seems to be unrelated to the specific symbols that my program is missing, and/or can be typographical in nature. So, unfortunately, I've had to create another thread about this.
My program can not find the symbols average, max, min, and et cetera. I believe that I may have done my arithmetic algorithms wrong, and they are either not initialized properly or at all, or I need to set them to zero before the switch command is ever used.
I'll need to post the code so you can see what I have done:
>public static void main( String args[] )
{
// Attempting to initialize the 3 integers AND the user-input early on
int n1, n2, n3, n4;
Scanner sc = new Scanner( System.in);
while ( true )
{
System.out.println ( "Please give three integers separated by spaces: " );
n1 = sc.nextInt();
n2 = sc.nextInt();
n3 = sc.nextInt();
// building a menu - hoping integers aboive will work in Switch command
System.out.println( "\n****** Analysis Menu ******" );
System.out.println( "1: Average" );
System.out.println( "2: Maximum" );
System.out.println( "3: Minimum" );
System.out.println( "4: Total" );
System.out.println( "5: Exit" );
System.out.println( "*******************\n" );
n4 = sc.nextInt(); // get the user selection
if ( n4 == 1 )
{
Average = n1 + n2 + n3 / 3;
System.out.print( "Average = " + Average );
}
else if ( n4 == 2 )
{
max = n1;
if ( max < n2 ) max = n2;
if ( max < n3 ) max = n3;
System.out.println( "Maximum = " + max );
}
else if ( n4 == 3 )
{
min = n1;
if ( min > n2) min = n3;
if ( min > n3) min = n2;
System.out.print( "Minimum = " + min );
}
else if ( n4 == 4 )
{
total = sum;
System.out.print( "total = " + total );
}
else if ( n4 == 5 )
{
System.out.println( "You have selected Exit." );
break;
}
else
{
System.out.println( "No such selection exists." );
The error messages say they cannot find every total, min, max, average, and sum in this. So I am not sure if I need to initialize them somehow, set them to 0, or even how to do that in this context.
There are multiple issues in above code:
1. Average, min, max variable not defined.
2. You average logic is not right.
3. You are missing end brace.
I tried to modify these and this is what i came up with.
public static void main( String args[] )
{
// Attempting to initialize the 3 integers AND the user-input early on
int n1, n2, n3, n4;
int Average, max, min, total;
Scanner sc = new Scanner( System.in);
while ( true )
{
System.out.println ( "Please give three integers separated by spaces: " );
n1 = sc.nextInt();
n2 = sc.nextInt();
n3 = sc.nextInt();
// building a menu - hoping integers aboive will work in Switch command
System.out.println( "\n****** Analysis Menu ******" );
System.out.println( "1: Average" );
System.out.println( "2: Maximum" );
System.out.println( "3: Minimum" );
System.out.println( "4: Total" );
System.out.println( "5: Exit" );
System.out.println( "*******************\n" );
n4 = sc.nextInt(); // get the user selection
if ( n4 == 1 )
{
Average = (n1 + n2 + n3) / 3;
System.out.print( "Average = " + Average );
}
else if ( n4 == 2 )
{
max = n1;
if ( max < n2 ) max = n2;
if ( max < n3 ) max = n3;
System.out.println( "Maximum = " + max );
}
else if ( n4 == 3 )
{
min = n1;
if ( min > n2) min = n3;
if ( min > n3) min = n2;
System.out.print( "Minimum = " + min );
}
else if ( n4 == 4 )
{
total = n1 + n2 + n3;
System.out.print( "total = " + total );
}
else if ( n4 == 5 )
{
System.out.println( "You have selected Exit." );
break;
}
else
{
System.out.println( "No such selection exists." );
}
}
}
You need to define Average,min,max,total as a variable just like n1,..,n4. I mean
decimal Average;
BTW it's better to avoid naming variable like this for example minValue or maxValue are better in naming.
Related
I modified the code to work with two files. to_search.txt has string to be searched. big_file.fastq has lines where to be searched and if string found (2 mismatch allowed with exact length which range from 8-10, no addition and deletion), place in respective name. So each string is searched in all lines (2nd line) in big_file.fastq.
# to_search.txt: (length can be from 8-20 characters)
1 TCCCTTGT
2 ACGAGACT
3 GCTGTACG
4 ATCACCAG
5 TGGTCAAC
6 ATCGCACA
7 GTCGTGTA
8 AGCGGAGG
9 ATCCTTTG
10 TACAGCGC
#2000 search needed
# big_file.fastq: 2 billions lines (each 4 lines are associated: string search is in second line of each 4 lines).
# Second line can have 100-200 characters
#M04398:19:000000000-APDK3:1:1101:21860:1000 1:N:0:1
TCttTTGTGATCGATCGATCGATCGATCGGTCGTGTAGCCTCCAACCAAGCACCCCATCTGTTCCAAATCTTCTCCCACTGCTACTTGAAGACGCTGAAGTTGAAGGGCCACCTTCATCATTCTGG
+
#8ACCDGGGGGGGGGGGGGEGGGGGGGGDFFEGGG#FFGGGGGGGGGGGGGGGGGCF#<FFGGGGGFE9FGGGFEACE8EFFFGGGGGF9F?CECEFEG,CFGF,CF#CCC?BFFG<,9<9AEFG,,
#M04398:19:000000000-APDK3:1:1101:13382:1000 1:N:0:1
NTCGATCGATCGATCGATCGATCGATCGTTCTGAGAGGTACCAACCAAGCACACCACGGGCGACACAGACAGCTCCGTGTTGAACGGGTTGTTCTTCTTCTTGCCTTCATCATCCCCATCCTCAGTGGACGCAGCTTGCTCATCCTTCCTC
+
#8BCCGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
#M04398:19:000000000-APDK3:1:1101:18888:1000 1:N:0:1
NCAGAATGAGGAAGGATGAGCCCCGTCGTGTCGAAGCTATTGACACAGCGCTATTCCGTCTTTATGTTCACTTTAAGCGGTACAAGGAGCTGCTTGTTCTGATTCAGGAACCGAACCCTGGTGGTGTGCTTGGTTGGCAAGTTTACGGCTC
+
#8BCCGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGCGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGFGGGGGGGGGGGGGGGGGGGGGGGGGGGE
Here is the code for two mismatches. I tried with exact match, speed is not bad: takes around a day. I have used Time::Progress module. When I use 2 mismatch: shows 115 days to finish. How the speed can be improved here?
#!/usr/bin/perl
use strict;
use warnings;
$| = 1;
open( IN_P1, "big_file.fastq" ) or die "File not found";
my ( #sample_file_names, #barcode1 );
open( BC_FILE, "to_search.txt" ) or die "No barcode file";
my #barcode_file_content = <BC_FILE>;
foreach (#barcode_file_content) {
chomp $_;
$_ =~ s/\r//;
$_ =~ s/\n//;
#print $_;
my #elements = split( "(\t|,| )", $_ );
push #sample_file_names, $elements[0];
push #barcode1, $elements[2];
}
# open FH
my #fh_array_R1;
foreach (#sample_file_names) {
chomp $_;
local *OUT_R1;
open( OUT_R1, ">", "$_\.fq" ) or die "cannot write file";
push #fh_array_R1, *OUT_R1;
}
# unknown barcode file
open( UNKNOWN_R1, ">unknown-barcode_SE.fq" ) or die "cannot create unknown-r1 file";
while ( defined( my $firstp1 = <IN_P1> ) ) {
my $p1_first_line = $firstp1;
my $p1_second_line = <IN_P1>;
my $p1_third_line = <IN_P1>;
my $p1_fourth_line = <IN_P1>;
chomp( $p1_first_line, $p1_second_line, $p1_third_line, $p1_fourth_line, );
my $matched_R1 = "$p1_first_line\n$p1_second_line\n$p1_third_line\n$p1_fourth_line\n";
for ( my $j = 0 ; $j < scalar #barcode1 ; $j++ ) {
chomp $barcode1[$j];
my $barcode1_regex = make_barcode_fragments( $barcode1[$j] );
if ( $p1_second_line =~ /$barcode1_regex/i ) {
# keep if matched
print { $fh_array_R1[$j] } $matched_R1;
last;
}
else {
#print to unknown;
print UNKNOWN_R1 $matched_R1;
}
}
}
# make two mismatch patterm of barcode
sub make_barcode_fragments {
my ($in1) = #_;
my #subpats;
for my $i ( 0 .. length($in1) - 1 ) {
for my $j ( $i + 1 .. length($in1) - 1 ) {
my $subpat = join( '',
substr( $in1, 0, $i ),
'\\w', substr( $in1, $i + 1, $j - $i - 1 ),
'\\w', substr( $in1, $j + 1 ),
);
push #subpats, $subpat;
}
}
my $pat = join( '|', #subpats );
#print $pat;
return "$pat";
}
exit;
If your algorithm cannot be changed/improved in Perl itself, you can still get speedup by writing the time consuming parts in C. Here is an example using inline C:
use strict;
use warnings;
use Benchmark qw(timethese);
use Inline C => './check_line_c.c';
my $find = "MATCH1";
my $search = "saasdadadadadasd";
my %sub_info = (
c => sub { check_line_c( $find, $search ) },
perl => sub { check_line_perl( $find, $search ) },
);
timethese( 4_000_000, \%sub_info );
sub check_line_perl {
my ($find, $search ) = #_;
my $max_distance = 2;
for my $offset ( 0 .. length($search) - length($find) ) {
my $substr = substr( $search, $offset, length($find) );
my $hd = hd( $find, $substr );
if ( $hd <= $max_distance ) {
return ( $hd, $substr );
}
}
return ( undef, undef );
}
sub hd {
return ( $_[0] ^ $_[1] ) =~ tr/\001-\377//;
}
where check_line_c.c is:
void check_line_c( char* find, char * search ) {
int max_distance = 2;
int flen = strlen(find);
int last_ind = strlen(search) - flen;
SV *dis = &PL_sv_undef;
SV *match = &PL_sv_undef;
for ( int ind = 0; ind <= last_ind; ind++ )
{
int count = 0;
for ( int j = 0; j < flen; j++ )
{
if ( find[j] ^ search[ind+j] ) count++;
}
if ( count < max_distance )
{
match = newSV(flen);
sv_catpvn(match, search+ind, flen );
dis = newSViv(count);
break;
}
}
Inline_Stack_Vars;
Inline_Stack_Reset;
Inline_Stack_Push(sv_2mortal(dis));
Inline_Stack_Push(sv_2mortal(match));
Inline_Stack_Done;
}
The output is (Ubuntu Laptop using Intel Core i7-4702MQ CPU #2.20GHz):
Benchmark: timing 4000000 iterations of c, perl...
c: 2 wallclock secs ( 0.76 usr + 0.00 sys = 0.76 CPU) # 5263157.89/s (n=4000000)
perl: 19 wallclock secs (18.30 usr + 0.00 sys = 18.30 CPU) # 218579.23/s (n=4000000)
So this gives a 24-fold speedup for this case.
I'd suggest creating a really bad hashing algorithm. Something nice and reversible and inefficient, like the sum of the characters. Or maybe the sum of unique values (1-4) represented by the characters.
Compute the target sums, and also compute the maximum allowed variance. That is, if the objective is a match with two substitutions, then what is the maximum possible difference? (4-1 + 4-1 = 6).
Then, for each "window" of text of the appropriate length in the target data file, compute a running score. (Add a character to the end, drop a character from the start, update the hash score.) If the score for a window is within the allowable range, you can do further investigation.
You might want to implement this as different passes. Possibly even as different stages in a shell pipeline or script. The idea being that you might be able to parallelize parts of the search. (For instance, all the match strings with the same length could be searched by one process, since the hash windows are the same.)
Also, of course, it is beneficial that you can keep your early work if your program crashes in the later stages. And you can even have the early parts of the process running while you are still developing the end stages.
So, I have been doing this question :
Q. Write a program that lets users keep track of the last time they talked to each of their friends. Users should be able to add new friends (as many as they want!) and store the number of days ago that they last talked to each friend. Let users update this value as well.
I have created pointer to pointer user_friends to store the 2D string array for names of friends and no. of days since last talked. It's a 3x2 array initially for 3 friends. The 2 columns store friend's name and no. of days ( both in string type pointer array ).
My main has this :
int tsize = 3;
string **user_friends = new string*[tsize];
for ( int i = 0; i < tsize; i++ )
{
user_friends[i] = new string[2];
}
Here is the addFriends function to add friends in array.
void addFriends( string **user_f , int tsize )
{
static int next_friend = 0;
int index = 0;
string days;
if ( next_friend >= tsize )
{
cout << "\nGrowing array now...";
user_f = growArray ( user_f, tsize );
}
cout << "\n\nEnter index : ";
cin >> index;
cin.ignore();
cout << "\nEnter friend's name : ";
getline( cin, user_f[index][0] );
cout << "\nEnter days since last talked with this friend : ";
getline (cin, days);
user_f[index][1] = days;
next_friend++;
}
Then there is this growArray function to expand the memory allocated to string array :
string **growArray ( string **ptr, int cur_size )
{
string **new_ptr = new string*[ cur_size*2 ];
for ( int i = 0; i < cur_size; ++i )
{
new_ptr[i] = new string[2];
}
for( int i = 0; i < cur_size; ++i )
{
new_ptr[i] = ptr[i];
}
for ( int i = 0; i < cur_size; ++i )
{
for ( int j = 0; j < 2; ++j)
{
new_ptr[i][j] = ptr[i][j];
}
}
for ( int i = 0; i < cur_size; ++i )
{
delete ptr[i];
}
delete[] ptr;
return new_ptr;
}
Then this display function to print the array.
void displayFriends( string **user_f, int tsize )
{
for ( int i = 0; i < tsize; ++i )
{
for( int j = 0; j < 2; ++j )
{
cout << user_f[i][j] << "\t";
}
cout << endl;
}
}
Now, when I have entered upto 3 friends details, the program runs fine.
When I start to enter the details of friend 4 ( i.e. When I type in index as 3 ) the program crashes. Is there any problem with the growArray function ?
Also, is the display function alright ?
In the growArray function the first for loop should iterate from 0 to 2 * cur_size instead of 0 to cur_size.
for(int i = 0; i< 2 * cur_size; i++)
new_ptr[i] = new string[2]
how do i avoid using pointer variables and pointer-based pass-by-reference in this program? as my instructor said there is no need to use pointers. This is a the tortoise and the hare simulator , you will use number generation to develop a simulation of this memorable event.
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
#include <iomanip>
using std::setw;
const int RACE_END = 70;
// prototypes
void moveTortoise( int *const );
void moveHare( int *const );
void printCurrentPositions( const int *const, const int *const );
int main()
{
int tortoise = 1;
int hare = 1;
int timer = 0;
srand( time( 0 ) );
cout << "ON YOUR MARK, GET SET\nBANG !!!!"
<< "\nAND THEY'RE OFF !!!!\n";
// loop through the events
while ( tortoise != RACE_END && hare != RACE_END )
{
moveTortoise( &tortoise );
moveHare( &hare );
printCurrentPositions( &tortoise, &hare );
timer++;
} // end loop
if ( tortoise >= hare )
cout << "\nTORTOISE WINS!!! YAY!!!\n";
else
cout << "\nHare wins. Yuch.\n";
cout << "\nTIME ELAPSED = " << timer << " seconds" << "\n" << endl;
system("pause");
return 0; // indicates successful termination
} // end main
// progress for the tortoise
void moveTortoise( int * const turtlePtr )
{
int x = 1 + rand() % 10; // random number 1-10
if ( x >= 1 && x <= 5 ) // fast plod
*turtlePtr += 3;
else if ( x == 6 || x == 7 ) // slip
*turtlePtr -= 6;
else // slow plod
++( *turtlePtr );
if ( *turtlePtr < 1 )
*turtlePtr = 1;
else if ( *turtlePtr > RACE_END )
*turtlePtr = RACE_END;
} // end function moveTortoise
// progress for the hare
void moveHare( int * const rabbitPtr )
{
int y = 1 + rand() % 10; // random number 1-10
if ( y == 3 || y == 4 ) // big hop
*rabbitPtr += 9;
else if ( y == 5 ) // big slip
*rabbitPtr -= 12;
else if ( y >= 6 && y <= 8 ) // small hop
++( *rabbitPtr );
else if ( y > 8 ) // small slip
*rabbitPtr -= 2;
if ( *rabbitPtr < 1 )
*rabbitPtr = 1;
else if ( *rabbitPtr > RACE_END )
*rabbitPtr = RACE_END;
} // end function moveHare
// display new position
void printCurrentPositions( const int * const snapperPtr,
const int * const bunnyPtr )
{
if ( *bunnyPtr == *snapperPtr )
cout << setw( *bunnyPtr ) << "OUCH!!!";
else if ( *bunnyPtr < *snapperPtr )
cout << setw( *bunnyPtr ) << 'H'
<< setw( *snapperPtr - *bunnyPtr ) << 'T';
else
cout << setw( *snapperPtr ) << 'T'
<< setw( *bunnyPtr - *snapperPtr ) << 'H';
cout << '\n';
} // end function printCurrentPositions
In C++ you can use references instead of pointers. For example, instead of
void foo(int *x) {
*x = *x + 1;
}
int main() {
int a = 0;
foo(&a);
return 0;
}
you can pass x by reference, like so:
void foo(int &x) {
x = x + 1;
}
int main() {
int a = 0;
foo(a);
return 0;
}
Passing a reference is sort of like passing a pointer, except you don't need to dereference the pointer every time you want to access the value it points to.
You can google "C++ pass by reference" for more information, such as this tutorial: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Alternatively, in your program, you could simply pass int arguments and return the new value:
int moveTortoise(int turtle) {
...
turtle = turtle + 3;
...
return turtle;
}
tortoise = moveTortoise(tortoise)
References& and pointers* are usefull when:
1. you deal with instances of complex classes that passing by reference is resource(CPU time & main memory) consuming operation;
2. when you want to change arguments what are passed(as any function in C++ can return only one value, opposit for ex. to python where multiply values can be returned, you can cope with that restriction by passing using & or *);
3. Other cases...
Built-in(atomic) types can be passed by value (which is you case) without decrease in efficiency.
I'm trying to use Thrust to detect if each element of an array can be found in another array and where (both arrays are sorted). I came across the vectorized search routines (lower_bound and binary_search).
lower_bound will return for each value the index where it could be inserted in a list respecting its ordering.
I also need to know if the value is found or not (which can be done with binary_search), not just its position.
Is it possible to achieve both efficiently without making two searches (calling binary_search and then lower_bound)?
I know in the scalar case, lower_bound will return a pointer to end of the array if a value cannot be found, but this does not happens in the vectorized version.
Thanks!
You can check that the element that lower_bound returns is the same as the one you searched for. E.g. given a = {1,3,5} and searching for b = {1,4}, the result will be c = {0,2}. We have a[c[0]] == b[0], so b[0] is in a, but a[c[1]] != b[1] so b[1] is not in a.
(Note that you will need to ensure that you don't make any out-of-bounds memory accesses, since lower_bound can return an index that is beyond the end of the array.)
#tat0: you can also play around with Arrayfire:
vectorized search using lower_bound() does not give you the answer immediately
while with setintersect() in arrayfire, you get the "intersection" of two arrays directly:
float A_host[] = {3,22,4,5,2,9,234,11,6,17,7,873,23,45,454};
int szA = sizeof(A_host) / sizeof(float);
float B_host[] = {345,5,55,6,7,8,19,2,63};
int szB = sizeof(B_host) / sizeof(float);
// initialize arrays from host data
array A(szA, 1, A_host);
array B(szB, 1, B_host);
array U = setintersect(A, B); // compute intersection of 2 arrays
int n_common = U.elements();
std::cout << "common: ";
print(U);
the output is:
common: U = 2.0000
5.0000
6.0000
7.0000
to get the actual locations of these elements in array A, you can use the following
construct (provided that elements in A are unique):
int n_common = U.elements();
array loc = zeros(n_common); // empty array
gfor(array i, n_common) // parallel for loop
loc(i) = sum((A == U(i))*seq(szA));
print(loc);
then: loc =
4.0000
3.0000
8.0000
10.0000
Furthermore, thrust::lower_bound() seems to be slower than setintersect(),
i benchmarked it with the following program:
int *g_data = 0;
int g_N = 0;
void thrust_test() {
thrust::device_ptr<int> A = thrust::device_pointer_cast((int *)g_data),
B = thrust::device_pointer_cast((int *)g_data + g_N);
thrust::device_vector<int> output(g_N);
thrust::lower_bound(A, A + g_N, B, B + g_N,
output.begin(),
thrust::less<int>());
std::cout << "thrust: " << output.size() << "\n";
}
void af_test()
{
array A(g_N, 1, g_data, afDevicePointer);
array B(g_N, 1, g_data + g_N, afDevicePointer);
array U = setintersect(A, B);
std::cout << "intersection sz: " << U.elements() << "\n";
}
int main()
{
g_N = 3e6; // 3M entries
thrust::host_vector< int > input(g_N*2);
for(int i = 0; i < g_N*2; i++) { // generate some input
if(i & 1)
input[i] = (i*i) % 1131;
else
input[i] = (i*i*i-1) % 1223 ;
}
thrust::device_vector< int > dev_input = input;
// sort the vector A
thrust::sort(dev_input.begin(), dev_input.begin() + g_N);
// sort the vector B
thrust::sort(dev_input.begin() + g_N, dev_input.begin() + g_N*2);
g_data = thrust::raw_pointer_cast(dev_input.data());
try {
info();
printf("thrust: %.5f seconds\n", timeit(thrust_test));
printf("af: %.5f seconds\n", timeit(af_test));
} catch (af::exception& e) {
fprintf(stderr, "%s\n", e.what());
}
return 0;
}
and the results:
CUDA toolkit 4.2, driver 295.59
GPU0 GeForce GT 650M, 2048 MB, Compute 3.0 (single,double)
Memory Usage: 1937 MB free (2048 MB total)
thrust: 0.13008 seconds
arrayfire: 0.06702 seconds
UINT itemLength = strValue.length();
bRet = ( ( itemLength > maxLength ) || ( itemLength < minLength ) ) ? VARIANT_FALSE : VARIANT_TRUE;
This code is being used for Length validation.
I want to validate number:
For Ex:
min value = 0, Max value =10, original value = 5
In this condition i want to check only whole number.
For Ex, I want to display following:
Input -> Output
5 -> True
5.1 -> False i want to display.
assuming f as precision number try this
if (f % (int)f > 0)
{
Console.WriteLine("is not whole number");
}
else
{
Console.WriteLine("is whole number");
}