How It Works

InstaEDU makes it easy to find a great tutor and connect instantly

  • Connect with the perfect tutor, anytime 24/7

    Never get stuck on homework again. InstaEDU has awesome tutors instantly available around the clock.

  • Work together with the best lesson tools

    Our lesson space lets you use video, audio or text. Upload any assignment and work through it together.

  • Try it free—then lock in a super low rate

    Anyone can try InstaEDU for up to 2 hours for free. After that, rates start at just 40¢/minute.

See all Sam's info

Teaching Experience

My major made me really strong in programing languages and math. I have been working as a private tutor since I started college. but I have also helped my friends understand math since I was in High School. Java , C/C++ , and most other computer languages.

Extracurricular Interests

I was born in Michigan. I speak both English and Arabic Fluently.

Top Subjects

Algebra

It's very easy for me so I can help

Arabic

It's my language and I used to be a language partner so I know how to  help

Basic Math

math is my strength and what I love

Calculus

I can easily help with anything when it comes to calculus.

College Admissions

I can help with the math part

Computer Science

I'm very strong in programing languages such as Java, C, C++ and C#. I will be happy to help.

Electrical Engineering

I'm good at it because I took so many classes.

Geometry

Math has been the subject I loved since I started learning it. and I'm really good at it.

Geometry (College Advanced)

I enjoy helping people with all math subjects.

Linear Algebra

I'm good at it because I've used it in so many classes and I have helped students before

Pre-Algebra

I have helped many students.

Pre-Calculus

I love math

SAT II Mathematics Level 1

I have helped many students before

SAT II Mathematics Level 2

I guarantee that you will get the best help

Trigonometry

I have taken the class  and I have used it with most of my engineering classes.

Ruby Programming This is a review for a written lesson.
Ruby Programming This is a review for a written lesson.
Ruby Programming This is a review for a written lesson.
Java Programming
Java Programming "Great help! Give him whatever questions you have and no matter how long it takes, he'll figure it out."
Java Programming "Very patient. He quickly analyzed the problem and came up with more than one solution. "
C++ Programming This is a review for a written lesson.
Java Programming
Java Programming "j"
Ruby Programming "Great Guy Fast and Answered all my questions in Ruby"
1-10 of 49 Reviews

Subject: Ruby Programming

Someone asked:

I need a tutor to do the second problems of this a5 assignment.

  • a5.pdf This attachment has been locked.

Sam responded:

Part 4:
A)
This is the regular expression that you will need to match this.
/^\d\.+\d$/
Check if the line matches this and then you can just return it.

B)

This regular expression will math any sentence:
[A-z]{1}\s?[a-z]*\s?\!?\??

again make a method then check if the given string matches this regular expression and return it if it does.

c) For this part it's asking you to define a method that will match a file path for unix. To do this you will need to use some regular expressoin and check if it's equal (~=) some path that you are matching to. Here is the regExpression that you have to use: \A(?:[0-9a-zA-Z_-]+\/?)+\z. The parenthesis indicate the numbers of $. which you could easily chose as your choice. you will have an if statment that will check if it's matching and if it's not then you set that string equal to "" ( empty String).

D) a5/re.1
To match this with a method:
def calc_re str
if str ~= /(a5/re.1)$/ then
//Found.
end
end

Feedback:

Subject: Ruby Programming

Someone asked:

I need a tutor to do the fourth problem (re.rb) of this a5 assignment.

  • a5.pdf This attachment has been locked.

Sam responded:

Part 4:
A)
This is the regular expression that you will need to match this.
/^\d\.+\d$/
Check if the line matches this and then you can just return it.

B)

This regular expression will math any sentence:
[A-z]{1}\s?[a-z]*\s?\!?\??

again make a method then check if the given string matches this regular expression and return it if it does.

c) For this part it's asking you to define a method that will match a file path for unix. To do this you will need to use some regular expressoin and check if it's equal (~=) some path that you are matching to. Here is the regExpression that you have to use: \A(?:[0-9a-zA-Z_-]+\/?)+\z. The parenthesis indicate the numbers of $. which you could easily chose as your choice. you will have an if statment that will check if it's matching and if it's not then you set that string equal to "" ( empty String).

D) a5/re.1
To match this with a method:
def calc_re str
if str ~= /(a5/re.1)$/ then
//Found.
end
end

Feedback:

Subject: Java Programming

Someone asked:

working on a program that acts as a change dispenser but the program seems faulty and i can't figure out why

Sam responded:

hi,
It's better if you put down more details describing what you need help with. but, I've done the code in my computer and it works. Please message me if you have any questions but this should be working.

// CashDispenser.java
// Represents the cash dispenser of the ATM

public class CashDispenser
{
// the default initial number of bills in the cash dispenser
private final static int INITIAL_COUNT = 500;
private int count; // number of $20 bills remaining

// no-argument CashDispenser constructor initializes count to default
public CashDispenser()
{
count = INITIAL_COUNT; // set count attribute to default
} // end CashDispenser constructor

// simulates dispensing of specified amount of cash
public void dispenseCash( int amount )
{
int billsRequired = amount / 20; // number of $20 bills required
count -= billsRequired; // update the count of bills
} // end method dispenseCash

// indicates whether cash dispenser can dispense desired amount
public boolean isSufficientCashAvailable( int amount )
{
int billsRequired = amount / 20; // number of $20 bills required

if ( count >= billsRequired )
return true; // enough bills available
else
return false; // not enough bills available
} // end method isSufficientCashAvailable
} // end class CashDispenser

Subject: Ruby Programming

Someone asked:

given:

info = "2014-03-23 10:43:49 -0400"

How do I print out just the date format "2014-03-23" in ruby?

Sam responded:

you can do that using regular expression matching. But really the easiest way to do this is just using those easy steps. I"m going to give you two options. They both work:
1 ) puts info[0, s.length - 15]
2) puts info[0..-15]

Those should work.
message me if you have any questions.

Feedback:

Subject: Java Programming

Someone asked:

Help from before, how do I make my iterator work. (got it working)

Sam responded:

Hi,

for java I'll write you an example in how to use an itirator. if this is not what you are looking or message me and I will clarify more :). but this should help a lot. I'll write this exampl and hope you can follow and do the same for your work.

import java.util.*;

public class IteratorDemo {

public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

// Use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
This would produce the following result:

Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

Subject: Java Programming

Someone asked:

Note: We are given the following binary search tree class code( attached file) and we are supposed to modify it by implementing lazy deletion (the code will also be copied and pasted here). The formal HW question is listed in the bottom.

Code 1: attached

Code 2:
/**
* internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
{
if (t == null )
return t; // Item not found; do nothing

int compareResult = x.compareTo( t.element );

if (compareResult < 0 )
t.left = remove( x, t.left );
else if( compareResult > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.element = findMin( t.right ).element;
t.right = remove( t.element, t.right );
}

else
t = ( t.left != null ) ? t.left : t.right;
return t;
}

Textbook HW Question: Weiss 4.16 Data Structures in Java 3rd edition

Redo the binary search tree class to implement lazy deletion. Note carefully that this affects all of the routines. Especially challenging are findMin and findMax, which must now be done recursively.

  • binary search tree code.txt This attachment has been locked.

Sam responded:

public class BinarySearchTree<AnyType extends Comparable<? super AnyType>>
{
private static class BinaryNode<AnyType>
{
// Constructors
BinaryNode( AnyType theElement )
{ this( theElement, null, null ); }

BinaryNode( AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt )
{ element = theElement; left = lt; right = rt; }

AnyType element; // The data in the node
BinaryNode<AnyType> left; // Left child
BinaryNode<AnyType> right; // Right child
}

private BinaryNode<AnyType> root;

public BinarySearchTree( )
{ root = null; }

public void makeEmpty( )
{ root = null; }
public boolean isEmpty( )
{ return root == null; }

public boolean contains( AnyType x )
{ return contains( x, root ); }

public void insert( AnyType x )
{ root = insert( x, root ); }
public void remove( AnyType x )
{ root = remove( x, root ); }

public int countNodes() {
return countNodes(root);
}

private int countNodes(BinaryNode<AnyType> t) {
return (t == null) ? 0 : 1 + countNodes(t.left) + countNodes(t.right);
}

public int countLeafs() {
return countLeafs(root);
}

private int countLeafs(BinaryNode<AnyType> t) {
return (t == null) ? 0 : ((t.left == null && t.right == null) ? 1 : countLeafs(t.left) + countLeafs(t.right));
}

public int countFullNodes() {
return countFullNodes(root);
}

private int countFullNodes(BinaryNode<AnyType> t) {
return (t == null) ? 0 : ((t.left != null && t.right != null) ? 1 + countFullNodes(t.left) + countFullNodes(t.right) : countFullNodes(t.left) + countFullNodes(t.right));
}

/**
* Internal method to find an item in a subtree.
* @param x is item to search for.
* @param t the node that roots the subtree.
* @return node containing the matched item.
*/
private boolean contains( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return false;

int compareResult = x.compareTo( t.element );

if( compareResult < 0 )
return contains( x, t.left );
else if( compareResult > 0 )
return contains( x, t.right );
else
return true; // Match
}

/**
* Internal method to find the smallest item in a subtree.
* @param t the node that roots the subtree.
* @return node containing the smallest item.
*/
private BinaryNode<AnyType> findMin( BinaryNode<AnyType> t )
{
if( t == null )
return null;
else if( t.left == null )
return t;
return findMin( t.left );
}

/**
* Internal method to find the largest item in a subtree.
* @param t the node that roots the subtree.
* @return node containing the largest item.
*/
private BinaryNode<AnyType> findMax( BinaryNode<AnyType> t )
{
if( t != null )
while( t.right != null )
t = t.right;

return t;
}

/**
* Internal method to insert into a subtree.
* @param x the item to insert.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return new BinaryNode<AnyType>( x, null, null );

int compareResult = x.compareTo( t.element );

if( compareResult < 0 )
t.left = insert( x, t.left );
else if( compareResult > 0 )
t.right = insert( x, t.right );
else
; // Duplicate; do nothing
return t;
}

/**
* Internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return t; // Item not found; do nothing

int compareResult = x.compareTo( t.element );

if( compareResult < 0 )
t.left = remove( x, t.left );
else if( compareResult > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.element = findMin( t.right ).element;
t.right = remove( t.element, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}

/**
* Print the tree contents in sorted order.
*/
public void printTree( )
{
if( isEmpty( ) )
System.out.println( "Empty tree" );
else
printTree( root );
}

/**
* Internal method to print a subtree in sorted order.
* @param t the node that roots the subtree.
*/
private void printTree( BinaryNode<AnyType> t )
{
if( t != null )
{
printTree( t.left );
System.out.println( t.element );
printTree( t.right );
}
}

}

Subject: Computer Science

Someone asked:

Who can help me edit a c++ code which it read the student.dat which include student's name id and enrollment course and then print out the student name list, course list enrollment and find student with ID of 0,3,or 1. I have did half of them. but error came out.

Sam responded:

/* To make any class in c++ or java or any language you will need to creat a constructor For the class alot with athor methods for the class. For this case I made a code that could help you understand what's going on and how to make your assighment. A constructor is the one that is responsible for creating teh objects of students. An object is something that is a collection of infomation about a student. So let's say we have some student "Jim" when making an object of that it is now refering to more information than just his name. So instead of refering to him by his name, age, and Id, we can just say object jim and this will contain all the three information about him. There is also a toString method which will print those infomation and is usually used when making an object. other methods can be added as well such as getters and setters as needed if you are making other classes. a getter can be used to get some information about an object student ( such as his name) and a setter can set his name, age, id or whatever as needed.

This is the example: read through it and let me know if you have any questions.
#include <iostream>
#include <conio.h>
using namespace std;

class Student {
private:
char name;
int idnumber;
char degree;
public:
Student(char,int,char);
void setName(char n){name = n;}
int getName(){return name;}
void setIdnumber(char id){idnumber = id;}
int getIdnumber(){return idnumber;}
void setDegree(char d){degree = d;}
int getDegree(){return degree;}
};
Student::Student(char n,int id,char d){
name = n;
idnumber = id;
degree = d;
}

int main(){
Student s1, s2;
s1.setName(Sara);
s1.setIdnumber(333);
s1.setDegree(A);
s2.setName(Jack);
s2.setIdnumber(222);
s2.setDegree(B);
cout << "name: " << s1.getName() << ",IDnumber: " << s1.getIdnumber() << ",Degree: " << s1.getDegree() << endl;
cout << "name: " << s2.getName() << ",IDnumber: " << s2.getIdnumber() << ",Degree: " << s2.getDegree() << endl;

getch();
return 0;
}

Subject: C++ Programming

Someone asked:

Working on a 5 card poker game (specifics with UML diagram in file below). I have already started working on it and created a card class. I am currently having trouble with my Deck class and have no idea where I am going wrong. Also having trouble how to display the Hand class. Would like to work through a work space to understand my mistakes.

  • Homework 2.pdf This attachment has been locked.

Sam responded:

//This will get you started.

#ifndef CARDHEADER_H
#define CARDHEADER_H
#include <vector>
enum Face{ Ace , Two , Three , Four , Five , Six , Seven , Eight , Nine, Ten , Jack , Queen , King };
enum Suit{ Diamonds , Hearts , Clubs , Spades };
class Card{
public:
Card( Face, Suit );
void get_cardvalues( Face & , Suit & );
private:
Face myFace;
Suit mySuit;
};
class Deck{
public:
Deck( void );
~Deck();
void shuffle_cards( bool swap = false );
void print_tostring();
private:
std::vector<Card> deck;
};
#endif
cardndeck.cc ( includes card & deck implementations )

#include <algorithm>
#include <iostream>
#include <ctime>
#include "cardheader.h"
using namespace std;
Card::Card( Face face, Suit suit ){
myFace = face;
mySuit = suit;
}
void Card::get_cardvalues( Face &face, Suit &suit ){
face = myFace;
suit = mySuit;
}
Deck::Deck(){
int counter = 0;
int i;
int j;

for( j = int( Ace ); j <= int( King ); j++ ){
for( i = int( Diamonds ); i <= int( Spades ); i++ ){
deck.push_back( Card( Face( i ) , Suit( j ) ) );
counter++;
}
}
}
Deck::~Deck(){

deck.clear();
}
void Deck::print_tostring(){

int i;
static const char *faces[] = { "Diamonds" , "Hearts" , "Clubs" , "Spades" };
static const char *suits[] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

for( i = 0; i < ( int )deck.size(); i++ ){
Face f_temp;
Suit s_temp;
deck[ i ].get_cardvalues( f_temp , s_temp );
cout << "[" << suits[ s_temp ] << " of " << faces[ f_temp ] << "]";
cout << endl;
}
cout << endl;

}
void Deck::shuffle_cards( bool swap ){
static bool swapper;

if( !swapper && swap ){
srand( unsigned( time( NULL )));
swapper = true;
}
random_shuffle( deck.begin() , deck.end() );
}

Feedback:

Subject: Computer Science (College Advanced)

Someone asked:

Consider the following Y86 code:

addl %eax %eax

mrmovl 0(%ecx) %ebx

cmpl %ebx %eax

How many pipeline stalls (or bubbles) are required when running the above code with and without forwarding?

  • q3.pdf This attachment has been locked.

Sam responded:

This actually depends in the pipline kind you have. Some of them are 4 stages and others are 5. I'm going to assume that you have a 5 stage pipeline:

you have: IM REG EX DM REG
IM REG EX DM REG
stall stall stall stall
IM REG .......

As you can see the firs instruction does not depend on the second instruction, but the third instruction is in fact using the first instuction. The execution stage (EX) is the one that calculates the value of the addition because it's the one that acesses the (ALU) . So there for you will not have that value untill the value is calculated then decoded in (DM) stage then Written back to the register in (REG, the last one) stage. After that is done and since it's written back at the second half of the instruction we will have 4 stalls (waits) cycles. There are ways to solve this by forwarding. meaning you can forward the value after the end of EX stage down. But the question didn't say that and usually those questions are like this. if they don't say anything you should assume that there is notthing and it's just a regular pipeline.

IM REG EX DM REG

IM = Fetch stage
REG = read from reg stage
EX = Execution stage (ALU)
DM = decoding stage
REG = write back stage.

let me know if you are confused with any of those parts.

I attached a picture of the forwarding I was talking about. you guys will cover that later.

Subject: C++ Programming

Someone asked:

This one is the correct one to do as well as the Algebra and lab 7, I submitted those other in error if there is another one.

  • Assignment_06.docx This attachment has been locked.

Sam responded:

//This is the first class:

package guiExample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MySTTest extends JFrame {

// variables used throughout class
private static JLabel output_of_Wu;
private static JPanel pan1,pan2;
private static JButton but1;





/**
* Creates & displays Celsius conversion window.
*/
public MySTTest() {
output_of_Wu = new JLabel("output");
createPanel();
addPanel();

}

private void createPanel()
{
pan1 = new JPanel();
but1 = new JButton("WhatsUP");
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
add(pan2);
but1ButtonActionPerformed(evt);
}
});

pan2 = new JPanel();
}

private void addPanel()
{
pan1.add(but1);
pan2.add(output_of_Wu);

add(pan1);


}


private void but1ButtonActionPerformed(ActionEvent evt) {

output_of_Wu.setText(MyTestControl.whatsUp());

}
}

//This is the second class which has e main and the method what's up:

package guiExample;

import javax.swing.JFrame;

public class MyTestControl {
public static void main(String[] args) {
JFrame frame = new MySTTest();
frame.setTitle("Test Software");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);

frame.setVisible(true);
}
public static String whatsUp(){
return "I'm working on a Java program";
}
}

/* when creating a new object of the first class the constructor is being called and then we have the first panel. Then when clicking the button "what's up" we will call the perform action for the button which in turn will call the whatUp() method in the other class. As I said you didn't provide the Student class which you had so this is a full program but it needs some modifiation ( just a little bit) if you send me the student class. If you have any questions or anything you can chat with me and we can modify it. But For now this is a working program with the needed requirement.

Message me if you need any help.

Subject: Computer Science (College Advanced)

Someone asked:

I have to implement a stack class in c++, using a vector. For push() I have:
void Stack<T>::push(T && x)
{
if(stackVector.size() >=stackVector.capacity())
{
stackVector.resize();
}
stackVector.push_back(x);
}
however we also have a function that looks like void Stack<T>::push(const T& x).
What is the difference between these two functions? Also, what is the different between these functions, and how do I implement them:
Stack();
Stack(const Stack <T> &);
Stack(Stack<T> &&);

Sam responded:

& is An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).

&& is an rvalues are defined by exclusion, by saying that every expression is either an lvalue or an rvalue. Therefore, from the above definition of lvalue, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.

Examples:

int globalvar = 20;

int& foo()
{
return globalvar;
}

int main()
{
foo() = 10;
return 0;
}

Here foo returns a reference, which is an lvalue, so it can be assigned to. Actually, the ability of C++ to return lvalues from functions is important for implementing some overloaded operators.

template<typename T>
void foo(T&&);
Here, the following apply:
When foo is called on an lvalue of type A, then T resolves to A& and hence, by the reference collapsing rules above, the argument type effectively becomes A&.
When foo is called on an rvalue of type A, then T resolves to A, and hence the argument type becomes A&&.

Subject: Computer Science

Someone asked:

Rewrite the selection sort (Programming Project 7 on page 287) so that it is a template function, with the template parameter specifying the type of data in each node. Your new selection sort function will use the template version of the node.

This is the project 7 from page 287:

Write a function that takes a linked list of
integers and rearranges the nodes so that the
integers stored are sorted into the order
smallest to largest, with the smallest integer in the
node at the head of the list. If the original list had any
integers occurring more than once, then the changed
list will have the same number of each integer. For
concreteness you will use lists of integers, but your
function should still work if you replace the integer
type with any other type for which the less-than op-
eration is part of a total order semantics. Use the fol-
lowing function prototype and specification:

void sort_list(node*& head_ptr);
// Precondition: head_ptr is a head pointer of
// a linked list of items, and these items can be
// compared with a less-than operator.
// Postcondition: head_ptr points to the head
// of a linked list with exactly the same entries
// (including repetitions if any), but the entries
// in this list are sorted from smallest to
// largest. The original linked list is no longer
// available.

Your procedure will implement the following algo-
rithm (which is often called selection sort): The al-
gorithm removes nodes one at a time from the
original list and adds the nodes to a second list until
all the nodes have been moved to the second list.
The second list will then be sorted.
// Pseudocode for selection sort
while (the first list still has some nodes)
{
1. Find the node with the largest item of all
the nodes in the first list.
2. Remove this node from the first list.
3. Insert this node at the head of the second
list.
}

After all the nodes are moved to the second list, the
pointer, head_ptr, can be moved to point to the
head of the second list. Note that your function will
move entire nodes, not just items, to the second list.
Thus, the first list will get shorter and shorter until it
is an empty list. Your function should not need to
call the new operator since it is just moving nodes
from one list to another (not creating new nodes).

Sam responded:

Node *selectionsort(Node *list)
{
Node *tmp=list, *tmp2, *prev, *iLst, *jLst;
Node *min;

if (!list)
{
//empty list no need sort
return list;
}
//swapping the nodes we require previous node (remember this is SLL)
prev = list;
for (iLst=list; iLst && iLst->next; iLst=iLst->next)
{
min = iLst;
for (jLst = iLst->next; jLst; jLst = jLst->next)
{
//get the minimum node
if (jLst->info < min->info)
{
//mark the minimum node we had encountered so far
min = jLst;
}
}
//swap the nodes if required
if (iLst != min)
{
tmp = min->next;
//go find min’s previous node (min node can be many nodes away from base node to be swapped)
for (tmp2=iLst;tmp2->next; tmp2=tmp2->next)
{
if (tmp2->next == min)
{
break;
}
}
//check whether node to swapped is in beggining (i.e. header node)
if (prev != iLst)
{
prev->next = min;
}
else
{
//as we do not have special header node, if the first node and some
//other node, need to be swapped, then update the list (makes new min node as
//logical header)
list = min;
}
//are nodes to be swapped neibgoring nodes?
if (iLst->next == min)
{
//nodes to be swapped are neibhoring nodes,
//then swap them simply
min->next = iLst;
iLst->next = tmp;
}
else
{
//nodes to be swapped are not neibhor nodes, they are apart
//so, consider all scenarios
min->next = iLst->next;
iLst->next = tmp;
tmp2->next = iLst;
}
//after swapping we’ve changed our iterator address, so
//assign correct position to contnue sorting..
iLst = min;
}
//readjust previous node before we move our list pointer
prev = iLst;
}
return list;
}

Subject: Computer Science (College Intro)

Someone asked:

write a 2d java program to assign passengers to seats on an airplane for C&B Airways. assume an airplane with the following seating system. The number represents the row and the letter represents the seat position. All the planes have 9 rows of 5 seats. the program should use defined constants where appropriate.

1......A B C D E

2......A B C D E

3......A B C D E

.

.

.

.

.

9......A B C D E

Letters A and E are window seats and letters B and C are aisle seats. the program should read in a letter request, R for reservation, F for free and P for print display.. R command may take a seat number (i.e., 2B) or a letter code (W ffor window, I foe aisle, and N for any seat). the program should assign the seat or indicate that the seat is unavailable (" This seat is not available or there are not anymore seats of this type"). The F command will be followed be a seat number (i.e., 7C) and should change the seat from 'X' to the appropriate letter, or indicate that the seat was not taken. The P command takes no information and displays the seats as indicated above. The program should process one additional command Q, that takes no arguments and prints out the final seat configuration and exits the program.

if the input is as indicated below, the output produced is displayed.

R 1A

R W

R 1

R 2C

R 1B

F 2B

P

F 1B

R 9C

R N

Q

SEAT 1A RESERVED

SEAT 1E RESERVED

SEAT 1B RESERVED

SEAT 2C RESERVED

SORRY SEAT 1B TAKEN

SORRY SEAT 2B WAS NOT RESERVED

1 X X C D X

2 A B X C D E

3 A B C D E

9 A B C D E

SEAT 1B IS AVAILABLE

SEAT 9C IS RESERVED

SEAT 1D IS RESERVED

1 X B C X X

2 A B X D E

3 A B C D E

9 A B X D E

THANK YOU FOR FLYING WITH C&B AIRWAYS!

I NEED BY 8:00 AM TOMORROW

Sam responded:

//Here is the program completed. As you can see the best way to work this out is //to use the cases and a while loop that keeps asking the user to enter something //until the "run" flag changes to false: please try to understand the code :).

//Best of luck

import java.util.Scanner;

public class Test2{
public static void main (String [] args){
// all nulls.
String [][]data_base = new String[100][5];
boolean run = true;

System.out.println("Hello, This is an AirPlain reservation system: ");
while(run){
System.out.println("please chose an optoin");
Scanner scan = new Scanner(System.in);
String input = scan.next();
input.replaceAll("\\s+","");
char[] charArray = input.toCharArray();

switch(charArray[0]){
case 'R': {
if(charArray[1] == 'W' || charArray[1] == 'I' || charArray[1] == 'N'){
if(charArray[1] == 'W'){
int flag =0;
// find window seat.
for(int i = 0; i<data_base.length;i++){
if(data_base[i][0] == null){
data_base[i][0] = "X";
flag =1;

break;
} else if(data_base[i][4] == null){
data_base[i][4] = "X";
flag = 1;
break;
}

}
if(flag ==0){
System.out.println("Seat not available");
}
}if(charArray[1] == 'I'){
//find iel seat:
int flag = 0;

for(int i = 0; i<data_base.length;i++){
if(data_base[i][1] == null){
data_base[i][1] = "X";
flag =1;
break;
} else if(data_base[i][2] == null){
data_base[i][2] = "X";
flag =1;
break;
}

}
if(flag ==0){
System.out.println("Seat not available");
}

}if(charArray[1] == 'N'){
//find any seat:
int flag = 0;
for(int i =0; i<data_base.length;i++){
for(int j=0;j<data_base[0].length;j++){
if(data_base[i][j] == null){
data_base[i][j] = "X";
flag =1;
break;
}
}
}
}
if(flag ==0){
System.out.println("Seat not available");
}
}else{
//we have a seat number exactly requested:
int flag =0;
char seatNumChar = charArray[1];
int seatNum = seatNumChar - 48;
if(charArray[2] == 'A'){
data_base[seatNum][0] = "X";
flag =1;
}else if(charArray[2] == 'B'){
data_base[seatNum][1] = "X";
flag =1;
}else if(charArray[2] == 'C'){
data_base[seatNum][2] = "X";
flag =1;
} else if(charArray[2] == 'D'){
data_base[seatNum][3] = "X";
flag =1;
}else if(charArray[2] == 'E'){
data_base[seatNum][4] = "X";
flag =1;
}
if(flag ==0){
System.out.println("Seat not available");
}
}
break;

}
case 'F':{
char seatNumChar = charArray[1];
int seatNum = seatNumChar - 48;

if(charArray[2] == 'A'){
if(data_base[seatNum][0] == "X"){
data_base[seatNum][0] = "A";
}else{
System.out.println("The seat was not taken");
}

} else if(charArray[2] == 'B'){
if(data_base[seatNum][1] == "X"){
data_base[seatNum][1] = "A";
}else{
System.out.println("The seat was not taken");
}
}else if(charArray[2] == 'C'){
if(data_base[seatNum][2] == "X"){
data_base[seatNum][0] = "C";
}else{
System.out.println("The seat was not taken");
}
}else if(charArray[2] == 'D'){
if(data_base[seatNum][3] == "X"){
data_base[seatNum][0] = "D";
}else{
System.out.println("The seat was not taken");
}
}else if(charArray[2] == 'E'){
if(data_base[seatNum][0] == "X"){
data_base[seatNum][0] = "E";
}else{
System.out.println("The seat was not taken");
}
}
break;
}
case 'P':{
for(int i =0;i<data_base.length;i++){
for(int j =0; j<data_base[0].length;j++){
System.out.println(i+"......." +data_base[i][j] +" ");

}

}
break;
}
case 'Q':{
System.out.println("THANK YOU FOR FLYING WITH C&B AIRWAYS!");
run = false;
break;
}
default:{
System.out.println("WRONG INPUT");
}
} // close the switch:

}

}
}

Feedback:

Subject: Computer Science (College Advanced)

Someone asked:

Hi. I am working on a program where I have to print out the top 10 most used characters, words and numbers from a file. I am using a map container to store each character/word/number, then putting that into a vector of pairs so it can be sorted. (Language is C++ by the way) For numbers and words, it is counting a blank space where is shouldn't. I have tried not isspace, not \0 and anything else I can think of. Any suggestions on what else to try?

Thanks
Sam

Sam responded:

Hi,
I would think the best solution to this is to design a method called split. this method will look at ur text file. split the words that are separated by anything you need (spaces in your case) and then store them in a vector. so your output will actually have a vector of all the strings you have in the file with no spaces at all. after having that vector you can retrieve the words however you like (add then to the map for in your example). Here is how you can do the split(...... , ......) function:

vector<string>& splitstring::split(char delim, int rep) {
if (!flds.empty()) flds.clear(); // empty vector if necessary
string work = data();
string buf = "";
int i = 0;
while (i < work.length()) {
if (work[i] != delim)
buf += work[i];
else if (rep == 1) {
flds.push_back(buf);
buf = "";
} else if (buf.length() > 0) {
flds.push_back(buf);
buf = "";
}
i++;
}
if (!buf.empty())
flds.push_back(buf);
return flds;
}

//I hope this explinatiion help, but if it doesn't message me and I will be happy to explain anything or add stuff if this solution isn't good for what you're doing.

best :)

Subject: Computer Science (College Advanced)

Someone asked:

Hi,
I am looking for help with PlayFair Cipher. I am given plaintext and corresponding cipher-text and I am asked to find the key/keyword. I just need guidance as to steps on recovering the text.

Sam responded:

Hi,
okay so if you are doing this with java or any other program this is pretty much what you have to do:
Firstly, you're game is a double array(or a 2 diminution array) which consist of characters in each element. To make a function or method that will find a given word in the parameter you will need to go to each element in the double array( which can be done by a nested for loops):
example: for(int i = 0; i<=arr.length;i++){
for(int j = 0; j<arr[0].length;j++){
// content of the method
}
After going to each element you will need another for loop inside (where it says "content of the method") to check if for each time you go left,right,up or down with the same distance as the length of the word or "string" given and check if it's that is equal to the word given. Be also certine to check if we are at the edge we will not need to go left for example because we will not have any elements there. going left and right shouldn't be hard but going up and down might be a bit tricky. but you can solve that by just holding the same col index and adding or subtracing (depending if it's up or down) to the row index so you can go up and down.

This should give you an idea of what's need to be done and how to do it. The best way to go about this problem is to have real example and work it out on paper to see if your implimantaiton works. :)

best of luck

Feedback:

Subject: C Programming

Someone asked:

Hi, this goes to anyone who can program well in C language. It is an easy assignment I simply do not have time to do, I have several other ones I need to get done :/. I am giving full 1 hour for someone to complete this, this is C not C++. Please do NOT use any C++ libraries in fact I think this can be done without using anything besides the standard library for the C language.

OK onto the assignment:
I need a program that can read in 5 currencies (Dollar, Euro, Yen, Rupee, and Pound) then I need it to organize this in stacks.
"construct a virtual money pile, which tracks each donation as it is placed in a pile with like currency, and then reads each pile of currency back out in reverse order."

So for example I enter $500, €350, ¥940, $420, $320, €555, INR 20
The output should look like:
$320
$420 €555
$500 €350 ¥940 INR 20
(INR standing for rupee symbol)

To read inputs I used: (Please use getchar)
C = getchar();
while (c != EOF) //EOF meaning end of file, represented by Ctrl-D
{
if ((c >= '0') && (c <= '9'));
{
x = x * 10 = (c- '0');
}
c = getchar();
printf('You entered" c);
---

Easy enough! Please help doing this, would really appreciate it.

Sam responded:

//Because stack if FILO (first in last out) we can make a use of that.

Stack s;
int flag = 1;
counter =0;
int numDon;
string money;
printf("how many donations u have? \n");
scanf ("%d",&numDon);
counter = numDon;
while(numDon){
printf ("Enter your donation one by one: \n");
scanf("%d", &money);
s.push(money);
numDon--;
}

//To print it:
int i;
for(i= 0; i<counter; i++){
String toPrint = s.pop;
printf("%s",toPrint);
}

Feedback:

Subject: C++ Programming

Someone asked:

Can someone help me write these method definitions?? I've attached the Class and Main. Please help!! Thank you.

Automaton(int rule) - a constructor. Through the mutator, below, we'll sanitize rule and then convert it to our internal representation. We also need to establish the seed: a single 1 in a sea of 0s (in this assignment a 1 means an asterisk, '*', and a 0 means a blank, ' '.

string toStringCurrentGen() - This returns a string consisting of the current generation, thisGen, but does so by embedding it in a returnString whose length is exactly displayWidth long. If thisGen is smaller than displayWidth, it is positioned in the center of the larger returnString, with the excess padded by extremeBit characters. If thisGen is longer than displayWidth, it has to be truncated (on both ends) so that it is perfectly centered in the returned returnString, any excess trimmed off both ends, equally.

Two Mutators:
bool setRule(int newRule) - converts the int newRule, a number from 0-255, to an array of eight bools. For example, if the newRule is 182, then this is the binary number 1 0 1 1 0 1 1 0, which means that the resultant array will be

rule[7] = true,
rule[6] = false ,
rule[5] = true,
rule[4] = true,
rule[3] = false,
rule[2] = true,
rule[1] = true ,
rule[0] = false.

As usual, this must sanitize the int so that only values in the legal range 0-255 are allowed.
bool setDisplayWidth(int width) - this is described by the earlier description of displayWidth and MAX_DISPLAY_WIDTH. I repeat that only odd widths are allowed (for centering purposes).

void propagateNewGeneration() - this is the workhorse function. It will use the three private members thisGen, extremeBit and rule[], and create the next generation from them. This method must first append two extremeBits to each side of thisGen in order to provide it with enough bits (or chars) on each end needed by rule. This adds four chars to thisGen, temporarily. We then apply rule in a loop to the new, larger, thisGen, which creates a separate (local) nextGen string. If you do this correctly, nextGen will be two characters smaller than the recently augmented thisGen (but still two larger than the original thisGen that entered the method). You must understand this statement, conceptually, before you write your first line of code, or you will be doomed. Then, you replace the old thisGen with our new nextGen.

In brief, we pad thisGen with four extremeBits, then apply rule, and we have a new nextGen, two larger than we started out with. We copy that back to thisGen to complete the cycle.

Finally, we have to apply rule to three consecutive extremeBits to figure out what the new extremeBit will be for the next generation (" " or "*"?) . What do I mean by "three consecutive"? We apply rule to an int representing a 3-bit pattern inside the old generation. In this case, we are doing this way out where all the bits are the same: extremeBit. So each input will be three 0s or three 1s -- an int 0 or an int 7 -- depending on the value of extremeBit. The result will enable us determine the new value of extremeBit. We must do this before we return, so extremeBit is correct for the next call to this method.
void resetFirstGen() - reloads thisGen and extremeBit to represent a 1 centered in a sea of 0s.

  • Automaton.txt This attachment has been locked.

Sam responded:

//Here you go:
//Thank you

#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <stdio.h>
#include <math.h>
using namespace std;

class Automaton
{
private:
bool rules[8];
string thisGen;
string extremeBit;
int displayWidth;

public:
static const int MAX_DISPLAY_WIDTH = 79;

Automaton(int rule);
string toStringCurrentGen();
bool setRule(int rule);
void resetFirstGen();
bool setDisplayWidth(int width);
void propagateNewGeneration();
string applyRule(string leftPos, string midPos, string rightPos);
};

int main()
{
int rule;

do
{
cout << "Enter Rule (0 - 255): ";
cin >> rule;
} while (rule < 0 || rule > 255);

Automaton Auto(rule);

cout << " Generation Start (0)" << endl;
for (int k = 0; k < 100; k++)
{
cout << Auto.toStringCurrentGen() << endl;
Auto.propagateNewGeneration();
}
cout << " Generation End (100)" << endl;
}

Automaton::Automaton(int rule)
{
setRule(rule);
resetFirstGen();
}

void Automaton::resetFirstGen()
{
this->displayWidth = MAX_DISPLAY_WIDTH;
this->extremeBit = " ";
this->thisGen = "*";
}

string Automaton::toStringCurrentGen()
{
string returnString;
returnString.resize(displayWidth, extremeBit[0]);
int retLength = returnString.length();
int genLength = thisGen.length();
int startPosLess = (retLength-genLength)/2;
int startPosGreat = (genLength-retLength)/2;

if(thisGen.length() == displayWidth)
return thisGen;
else if(thisGen.length() < displayWidth)
{
returnString.insert(startPosLess, thisGen);
returnString.erase(retLength, genLength);
thisGen = returnString;
return thisGen;
}
else if(thisGen.length() > displayWidth)
{
returnString.assign(thisGen, startPosGreat, retLength);
thisGen = returnString;
return thisGen;
}
}

bool Automaton::setRule(int rule)
{
int BitVal;

if (rule < 0 || rule > 255)
return false;

for(int k = 0; k < 8; k++)
{
BitVal = pow(2.0, 7-k);
if ((rule&BitVal) == 0)
rules[7-k] = false;
else if ((rule&BitVal) == 1)
rules[7-k] = true;
}

return true;
}

bool Automaton::setDisplayWidth(int width)
{
if(width > 0 && width <= MAX_DISPLAY_WIDTH &&
(width&1) == true)
{
this->displayWidth = width;
return true;
}
else
return false;
}

string Automaton::applyRule(string leftPos, string midPos, string rightPos)
{
string ruleString = leftPos + midPos + rightPos;
string retString;
int RuleNumber = 0;

for(int k = 0; k < 3; k++)
{
if(ruleString[k] == '*')
RuleNumber += pow(2.0, 2-k);
}

if(rules[RuleNumber])
retString = "*";
else if (!rules[RuleNumber])
retString = " ";

return retString;
}

void Automaton::propagateNewGeneration()
{
int BitValue;
string appExtremeBit, nextGen, leftPos, midPos, rightPos;

for(int k=0; k<2; k++)
appExtremeBit += extremeBit;

thisGen.insert(0, appExtremeBit);
thisGen.append(appExtremeBit);

for(int i = 1; i < thisGen.length()-1; i++)
nextGen += applyRule(leftPos=thisGen[i-1], midPos=thisGen[i],
rightPos=thisGen[i+1]);

thisGen = nextGen;

extremeBit = applyRule(extremeBit, extremeBit, extremeBit);
}

Feedback:

Subject: Physics

Someone asked:

Two identical permanent dipoles. each consisting of charges +q and -q separated by a distance s, are aligned along the x axis, a distance r from each other, where r>>s

(a) On your whiteboard draw a diagram like the one shown. Draw vectors showing all individual forces acting on each particle. Draw heavier vectors showing the net force on each dipole. How many external forces act on each dipole?

Sam responded:

Add up the forces for the point charges left dipole force consists of two attractive forces - two repulsive forces as shown here:

F(r,s) = k*q^2 * [1/(r-s)^2 + 1/(r+s)^2 - 2/r^2]

k = 1/(4*pi*e0) is the Coulomb's constant.

you now need to expand the factor in brackets as a Taylor expansion around s = 0.
we get:

[1/(r-s)^2 + 1/(r+s)^2 - 2/r^2] ~= (6s^2)/r^2 + (10s^4)/r^6 + ... O(s^6)

For s<< r, ignoring all except the first nonzero term in this expansion, so:

F(r,s) ~= 6*k*(q^2)*(s^2)/r^4

The magnitude of the force between widely separated dipoles (either electric or magnetic) varies as 1/r^4.

Subject: AP Computer Science A

Someone asked:

Here is the textbook with all the listings: http://www.cs.ccsu.edu/~jones/chap07.pdf
http://www.cs.ccsu.edu/~jones/chap05.pdf

Written lesson is not necessary, but please make sure the program is complied without error.
Please separate files by exercise name.

------------------------------------
1.Write a recursive method to compute a fibonocci series. Start at a user supplied starting point and continue 10 places.
-----------------------------------
2.Write a recursive method RevDigs that outputs its integer parameter with the digits reversed. For example RevDigs(147) outputs 741, RevDigs(4) outputs 4. You will have to use your modulus operator (%) and integer division.
---------------------------------
3.Write a program that prompts a professor to input grades for five different courses for 10 students. Prompt the professor to enter one grade at a time using the prompt "Enter grade for student #1" and "Enter grade #1". Verify that the prefessor enters only A,B,C,D, or F. Use variables for the student numbers ( 1 through 10) and grade numbers (1 through 5). Also have your program calculate the grade point average (GPA) for each student. A student receives four grade points for an A, three grade points for a B, two grade points for a C, one grade point for a D, and zero grade points for an F. Store the grades and points in parallel arrays. Search the arrays to determine the points for the grades. The class name is GradePoint.
----------------------------------
Part A Create a class for services offered by a hair styling salon. Data fields include a String to hold the service description (for example, "Cut", "Shampoo", or "Manicure"), a double to hold the price, and an integer to hold the average minutes it takes to perform the service. The class name is HairSalon. Include a constructor that requires arguments for all three data fields and three get methods that each return one of the data field's values ( getPrice() for example).

Part B Write a program named SortSalon that contains an array to hold six HairSalon objects and fill it with data. Include a method to sort the array in ascending order by price of service. Call the method and display the results.

Part C Add a method to the SortSalon program that sorts the HairSalon objects in descending order by time to perform the service. Call the method and display the results.

Part D Add a method to the SortSalon program that sorts the HairSalon objects in alphabetical order by service description. Call the method and display the results.

Part E Add a prompt to the SortSalon program giving the user three choices; sort by description, price, or time. Depending on the user's input, call one of the three sort methods and display the results.
-------------------------

Sam responded:

#1)
unsigned long fib(unsigned int n)
{
if (n == 0 || n == 1)
{
return n;
}
else
{
return fib(n - 1) + fib(n - 2);
}
}

#2)
public static void main(String[] args) {
//System.out.println("Reverse of no. is " + reversDigits(91));
reversDigits(98198187);

}

public static void reversDigits(long number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.println(number % 10);
reversDigits(number/10);
}
}

#3)
int questin =10;
while (question != 10) {
System.out.println("Enter The Correct Number ! ");
question = sc.nextInt();
question++;
}

Feedback:

Subject: Computer Science

Someone asked:

who can help me using unix (knoppix)??

Sam responded:

what do you need help with exactly? just the commands for unix in general? I can help you with that.
Here is a summary of all the commands you will need for unix:

//----------------------------------start here-----------------------------------------------------//
cat

This is one of the most flexible Unix commands. We can use to create, view and concatenate files. For our first example we create a three-item English-Spanish dictionary in a file called "dict."

% cat >dict
red rojo
green verde
blue azul
<control-D>
%
<control-D> stands for "hold the control key down, then tap 'd'". The symbol > tells the computer that what is typed is to be put into the file dict. To view a file we use cat in a different way:

% cat dict
red rojo
green verde
blue azul
%
If we wish to add text to an existing file we do this:
% cat >>dict
white blanco
black negro
<control-D>
%
Now suppose that we have another file tmp that looks like this:

% cat tmp
cat gato
dog perro
%
Then we can join dict and tmp like this:
% cat dict tmp >dict2
We could check the number of lines in the new file like this:

% wc -l dict2
8
The command wc counts things --- the number of characters, words, and line in a file.

chmod

This command is used to change the permissions of a file or directory. For example to make a file essay.001 readable by everyone, we do this:

% chmod a+r essay.001
To make a file, e.g., a shell script mycommand executable, we do this

% chmod +x mycommand
Now we can run mycommand as a command.
To check the permissions of a file, use ls -l . For more information on chmod, use man chmod.

cd

Use cd to change directory. Use pwd to see what directory you are in.

% cd english
% pwd
% /u/ma/jeremy/english
% ls
novel poems
% cd novel
% pwd
% /u/ma/jeremy/english/novel
% ls
ch1 ch2 ch3 journal scrapbook
% cd ..
% pwd
% /u/ma/jeremy/english
% cd poems
% cd
% /u/ma/jeremy
Jeremy began in his home directory, then went to his english subdirectory. He listed this directory using ls , found that it contained two entries, both of which happen to be diretories. He cd'd to the diretory novel, and found that he had gotten only as far as chapter 3 in his writing. Then he used cd .. to jump back one level. If had wanted to jump back one level, then go to poems he could have said cd ../poems. Finally he used cd with no argument to jump back to his home directory.

cp

Use cp to copy files or directories.
% cp foo foo.2
This makes a copy of the file foo.
% cp ~/poems/jabber .
This copies the file jabber in the directory poems to the current directory. The symbol "." stands for the current directory. The symbol "~" stands for the home directory.

date

Use this command to check the date and time.
% date
Fri Jan 6 08:52:42 MST 1995
echo

The echo command echoes its arguments. Here are some examples:

% echo this
this
% echo $EDITOR
/usr/local/bin/emacs
% echo $PRINTER
b129lab1
Things like PRINTER are so-called environment variables. This one stores the name of the default printer --- the one that print jobs will go to unless you take some action to change things. The dollar sign before an environment variable is needed to get the value in the variable. Try the following to verify this:

% echo PRINTER
PRINTER
ftp

Use ftp to connect to a remote machine, then upload or download files. See also: ncftp

Example 1: We'll connect to the machine fubar.net, then change director to mystuff, then download the file homework11:

% ftp solitude
Connected to fubar.net.
220 fubar.net FTP server (Version wu-2.4(11) Mon Apr 18 17:26:33 MDT 1994) ready.
Name (solitude:carlson): jeremy
331 Password required for jeremy.
Password:
230 User jeremy logged in.
ftp> cd mystuff
250 CWD command successful.
ftp> get homework11
ftp> quit
Example 2: We'll connect to the machine fubar.net, then change director to mystuff, then upload the file collected-letters:

% ftp solitude
Connected to fubar.net.
220 fubar.net FTP server (Version wu-2.4(11) Mon Apr 18 17:26:33 MDT 1994) ready.
Name (solitude:carlson): jeremy
331 Password required for jeremy.
Password:
230 User jeremy logged in.
ftp> cd mystuff
250 CWD command successful.
ftp> put collected-letters
ftp> quit
The ftp program sends files in ascii (text) format unless you specify binary mode:

ftp> binary
ftp> put foo
ftp> ascii
ftp> get bar
The file foo was transferred in binary mode, the file bar was transferred in ascii mode.
grep

Use this command to search for information in a file or files. For example, suppose that we have a file dict whose contents are

red rojo
green verde
blue azul
white blanco
black negro
Then we can look up items in our file like this;
% grep red dict
red rojo
% grep blanco dict
white blanco
% grep brown dict
%
Notice that no output was returned by grep brown. This is because "brown" is not in our dictionary file.

Grep can also be combined with other commands. For example, if one had a file of phone numbers named "ph", one entry per line, then the following command would give an alphabetical list of all persons whose name contains the string "Fred".

% grep Fred ph | sort
Alpha, Fred: 333-6565
Beta, Freddie: 656-0099
Frederickson, Molly: 444-0981
Gamma, Fred-George: 111-7676
Zeta, Frederick: 431-0987
The symbol "|" is called "pipe." It pipes the output of the grep command into the input of the sort command.
For more information on grep, consult

% man grep
head

Use this command to look at the head of a file. For example,

% head essay.001
displays the first 10 lines of the file essay.001 To see a specific number of lines, do this:

% head -n 20 essay.001
This displays the first 20 lines of the file.
ls

Use ls to see what files you have. Your files are kept in something called a directory.

% ls
foo letter2
foobar letter3
letter1 maple-assignment1
%
Note that you have six files. There are some useful variants of the ls command:

% ls l*
letter1 letter2 letter3
%
Note what happened: all the files whose name begins with "l" are listed. The asterisk (*) is the " wildcard" character. It matches any string.

lpr

This is the standard Unix command for printing a file. It stands for the ancient "line printer." See

% man lpr
for information on how it works. See print for information on our local intelligent print command.

mkdir

Use this command to create a directory.
% mkdir essays
To get "into" this directory, do
% cd essays
To see what files are in essays, do this:
% ls
There shouldn't be any files there yet, since you just made it. To create files, see cat or emacs.

more

More is a command used to read text files. For example, we could do this:

% more poems
The effect of this to let you read the file "poems ". It probably will not fit in one screen, so you need to know how to "turn pages". Here are the basic commands:

q --- quit more
spacebar --- read next page
return key --- read next line
b --- go back one page
For still more information, use the command man more.

mv

Use this command to change the name of file and directories.

% mv foo foobar
The file that was named foo is now named foobar

ncftp

Use ncftp for anonymous ftp --- that means you don't have to have a password.

% ncftp ftp.fubar.net
Connected to ftp.fubar.net
> get jokes.txt
The file jokes.txt is downloaded from the machine ftp.fubar.net.

print

This is a moderately intelligent print command.
% print foo
% print notes.ps
% print manuscript.dvi
In each case print does the right thing, regardless of whether the file is a text file (like foo ), a postcript file (like notes.ps, or a dvi file (like manuscript.dvi. In these examples the file is printed on the default printer. To see what this is, do

% print
and read the message displayed. To print on a specific printer, do this:
% print foo jwb321
% print notes.ps jwb321
% print manuscript.dvi jwb321
To change the default printer, do this:
% setenv PRINTER jwb321
pwd

Use this command to find out what directory you are working in.
% pwd
/u/ma/jeremy
% cd homework
% pwd
/u/ma/jeremy/homework
% ls
assign-1 assign-2 assign-3
% cd
% pwd
/u/ma/jeremy
%
Jeremy began by working in his "home" directory. Then he cd 'd into his homework subdirectory. Cd means " change directory". He used pwd to check to make sure he was in the right place, then used ls to see if all his homework files were there. (They were). Then he cd'd back to his home directory.

rm

Use rm to remove files from your directory.
% rm foo
remove foo? y
% rm letter*
remove letter1? y
remove letter2? y
remove letter3? n
%
The first command removed a single file. The second command was intended to remove all files beginning with the string "letter." However, our user (Jeremy?) decided not to remove letter3.

rmdir

Use this command to remove a directory. For example, to remove a directory called "essays", do this:

% rmdir essays
A directory must be empty before it can be removed. To empty a directory, use rm.

rsh

Use this command if you want to work on a computer different from the one you are currently working on. One reason to do this is that the remote machine might be faster. For example, the command

% rsh solitude
connects you to the machine solitude. This is one of our public workstations and is fairly fast.

See also: telnet

setenv

% echo $PRINTER
labprinter
% setenv PRINTER myprinter
% echo $PRINTER
myprinter
sort

Use this commmand to sort a file. For example, suppose we have a file dict with contents
red rojo
green verde
blue azul
white blanco
black negro
Then we can do this:
% sort dict
black negro
blue azul
green verde
red rojo
white blanco
Here the output of sort went to the screen. To store the output in file we do this:
% sort dict >dict.sorted
You can check the contents of the file dict.sorted using cat , more , or emacs .
tail

Use this command to look at the tail of a file. For example,

% tail essay.001
displays the last 10 lines of the file essay.001 To see a specific number of lines, do this:

% tail -n 20 essay.001
This displays the last 20 lines of the file.
tar

Use create compressed archives of directories and files, and also to extract directories and files from an archive. Example:

% tar -tvzf foo.tar.gz
displays the file names in the compressed archive foo.tar.gz while

% tar -xvzf foo.tar.gz
extracts the files.
telnet

Use this command to log in to another machine from the machine you are currently working on. For example, to log in to the machine "solitude", do this:

% telnet solitude
See also: rsh.

wc

Use this command to count the number of characters, words, and lines in a file. Suppose, for example, that we have a file dict with contents

red rojo
green verde
blue azul
white blanco
black negro
Then we can do this
% wc dict
5 10 56 tmp
This shows that dict has 5 lines, 10 words, and 56 characters.

The word count command has several options, as illustrated below:

% wc -l dict
5 tmp
% wc -w dict
10 tmp
% wc -c dict
56 tmp

//--------------------------------------------end here-----------------------------------------//

Subject: Computer Science (College Advanced)

Someone asked:

Hello my name is Ty and I am trying to write a PalidromeDriver.java (PLEASE SEE ATTACHED JAVA FILE) so that the data structures operate in O(1), or constant time. I have implemented the function is_palindrome() and most of the main loop but am now stuck at this part.

The program should do the following:
1. read in and store an integer defining the number of phrases to test,
2. read in each phrase, test the phrase, and store the result,
3. print the results.

You will need to implement the following: (optionally write the node, stack and queue classes in a separate files)
1. Stack.java - a standard stack data structure, supporting: push(), pop(), and isEmpty()

2. Queue.java - a standard queue data structure, supporting: enqueue(), dequeue(), and isEmpty()

3. CharNode.java - a simple Node class containing two public data fields: char data, CharNode next

These data structures must be implemented efficiently; in other words, each atomic operation (ie push()) should operate in O(1), or constant, time.

Example of Input/Output:

Input:
5
Madam, I'm Adam
Never odd or even
Go hang a salami; I'm a lasagna hog!
Taco-cat
This is not a palindrome.

Output:
Palindrome
Palindrome
Palindrome
Palindrome
Not a palindrome

Tips:
What the heck is a palindrome? A palindrome can be defined as a phrase that reads the same forwards or backwards, ignoring all whitespaces, non-alphabetical characters and capitalization. So, you may have to do some pre-processing on the input phrases..check out the String library in the Java API docs.

Thank-you very much for your help.

Sam responded:

Hi,

I will write you couple of methods that will help you check if a string is palindrome or not: you can use them to check if each line in the input is palindrome or not. reading a file shouldn't be hard. so this will help you a lot with the work.

public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}

///Second method:

boolean isPalindrome(String str) {
int n = str.length();
for( int i = 0; i < n/2; i++ )
if (str.charAt(i) != str.charAt(n-i-1)) return false;
return true;
}

//Use any of those methods by calling the method in each line of the input text file then write "palindrome" if the function returns true and "not a palindrome" if the function return false to the output text file.

Subject: Calculus

Someone asked:

thanks!!!

Sam responded:

Check the ZipFile plz. it has the solution. it's 2 pictures.

  • attachments.zip This attachment has been locked.

Feedback:

Subject: Calculus

Someone asked:

thanks!

Sam responded:

Please message me tomorrow and I will solve this for you as well. Thanks.

Subject: Calculus

Someone asked:

thanks~!

Sam responded:

I can help with this tomorrow. I really have to go to sleep. Please message me for the answer tomorrow.

Subject: C++ Programming

Someone asked:

Attached is what I've done so far. I've done 2 classes, and now I'm stuck on the Deck class. Just gonna show you the instructions for the Deck class. I really don't know how to construct it.

Deck: A class that represents the source of the cards for dealing and, as the game progresses, the place from which players can receive new cards (say, as they pick cards "from the deck" or when future hands are to be dealt from the same deck). Recall this picture, which relates the Deck to the various Hands that it creates through the process called "dealing":
pic of dealing

Let's deconstruct the meaning of this important class.

Deck: A Deck object is the source of all cards. It's where the dealer gets cards to deal, and if a player takes an individual card after the deal, he takes it from the Deck object. Naturally, the primary member here is an array of Card objects, much like Hand. We'll call this member cards[]. A deck normally consists of a single pack of cards: 52 cards (four suits of 13 values each). However, some games use two, three or more packs. If a card game requires two packs, then the deck will consist of two full 52-card packs: 104 cards. (Many games throw away some cards before beginning. For example Pinochle wants all cards with values 8-and-below to be taken out of the deck, but we will not trouble ourselves with this complexity.) A newly instantiated deck will have a multiple of 52 cards and will contain all the standard cards, so the number of cards in a newly instantiated deck will be 52, 104, 156, ..., i.e., numPacks × 52.

Clearly, we need an int like Hand's numCards, to keep track of how many cards are actually in the cards[] array. To this end, we'll use topCard (not numCards), since a deck typically removes and delivers cards to players from the top-of-the-deck, and this is a convenient variable to use for the number of cards as well as the position of the top of the deck.

There are a few other useful members (numPacks, for example). In addition to the the usual constructors and accessors, we'll want a dealCard() to return and remove the card at the top of the deck (which may be received by a client and added to some player's hand), and a shuffle() to re-order the cards in a random fashion. Also, we'll need to restock the deck (init()) to the original full condition in preparation for a fresh deal (we would certainly not want to re-instantiate a new deck when we have a perfectly good one available: garbage collection, done by us or by the operating system, is a resource we do not abuse).

Phase 1: The Deck Class

Public Static Class Constants

Define public ints like MAX_PACKS = 6 , NUM_CARDS_PER_PACK = 52 , and MAX_CARDS_PER_DECK = MAX_PACKS * MAX_CARDS_PER_DECK. Use them to their full benefit in the class code.

Private Static Member Data

Card masterPack[ NUM_CARDS_PER_PACK ]
This is a public static Card array, masterPack[], containing exactly 52 card objects, which includes all the standard cards. It will enable us to avoid capriciously and repeatedly declaring the same 52 cards which are needed as the game proceeds. In other words, once we have, say, a ('6', spades) Card constructed and stored (inside this masterPack[]), we use that same instance whenever we need it as a source to copy in various places, notably during a re-initialization of the Deck object; it will always be in the masterPack[] array for us to copy.

Private Member Data

Card cards[...];
int topCard;
int numPacks;
Public Methods

Deck(int numPacks = 1) - a constructor that populates the arrays and assigns initial values to members.
bool init(int numPacks = 1) - re-populate cards[] with the standard 52 × numPacks cards. We should not repopulate the static array, masterPack[], since that was done once, in the (first-invoked) constructor and never changes. If numPacks is out-of-range, return false without changing the object; else return true and make the change.
void shuffle() - mixes up the cards with the help of the standard random number generator.
Card dealCard() - returns and removes the card in the top occupied position of cards[].
An accessor for the int, topCard (no mutator.)
Card inspectCard(int k) - Accessor for an individual card. Returns a card with errorFlag = true if k is bad.
Private Methods

static void allocateMasterPack() - this is a method that will be called by the constructor. However, it has to be done with a very simple twist: even if many Deck objects are constructed in a given program, this static method will not allow itself to be executed more than once. Since masterPack[] is a static, unchanging, entity, it need not be built every time a new Deck is instantiated. So this method needs to be able to ask itself, "Have I been here before?", and if the answer is "yes", it will immediately return without doing anything; it has already built masterPack[] in a previous invocation.
Recommended test of Class Deck

Declare a deck containing two packs of cards. Do not shuffle. Deal all the cards in a loop until the deck is empty (dealt directly to the display/screen, not to any Hand objects just yet). Display each card as it comes off the deck. Next, reset the deck by initializing it again (to the same two packs). Shuffle the deck this time, and re-deal to the screen in a loop again. Notice that the cards are now coming off in a random order.

Repeat this double deal, unshuffled, then shuffled, but this time using a single pack deck.

Example Test Run of Card Class

/* ---------------------------------------------------------
K of Spades / Q of Spades / J of Spades / T of Spades / 9 of Spades / 8 of
Spades / 7 of Spades / 6 of Spades / 5 of Spades / 4 of Spades / 3 of Spade
s / 2 of Spades / A of Spades / K of Hearts / Q of Hearts / J of Hearts /
T of Hearts / 9 of Hearts / 8 of Hearts / 7 of Hearts / 6 of Hearts / 5 of
Hearts / 4 of Hearts / 3 of Hearts / 2 of Hearts / A of Hearts / K of Diamo
nds / Q of Diamonds / J of Diamonds / T of Diamonds / 9 of Diamonds / 8 of
Diamonds / 7 of Diamonds / 6 of Diamonds / 5 of Diamonds / 4 of Diamonds /
3 of Diamonds / 2 of Diamonds / A of Diamonds / K of Clubs / Q of Clubs / J
of Clubs / T of Clubs / 9 of Clubs / 8 of Clubs / 7 of Clubs / 6 of Clubs
/ 5 of Clubs / 4 of Clubs / 3 of Clubs / 2 of Clubs / A of Clubs / K of Sp
ades / Q of Spades / J of Spades / T of Spades / 9 of Spades / 8 of Spades
/ 7 of Spades / 6 of Spades / 5 of Spades / 4 of Spades / 3 of Spades / 2
of Spades / A of Spades / K of Hearts / Q of Hearts / J of Hearts / T of He
arts / 9 of Hearts / 8 of Hearts / 7 of Hearts / 6 of Hearts / 5 of Hearts
/ 4 of Hearts / 3 of Hearts / 2 of Hearts / A of Hearts / K of Diamonds /
Q of Diamonds / J of Diamonds / T of Diamonds / 9 of Diamonds / 8 of Diamond
s / 7 of Diamonds / 6 of Diamonds / 5 of Diamonds / 4 of Diamonds / 3 of Di
amonds / 2 of Diamonds / A of Diamonds / K of Clubs / Q of Clubs / J of Clu
bs / T of Clubs / 9 of Clubs / 8 of Clubs / 7 of Clubs / 6 of Clubs / 5 of
Clubs / 4 of Clubs / 3 of Clubs / 2 of Clubs / A of Clubs /

T of Hearts / T of Diamonds / A of Clubs / Q of Spades / 3 of Clubs / 8 of Diamo
nds / T of Clubs / 5 of Clubs / J of Clubs / 3 of Clubs / 3 of Diamonds / 3 of H
earts / 3 of Spades / 2 of Hearts / Q of Clubs / 7 of Spades / A of Spades / Q o
f Hearts / 6 of Spades / 5 of Clubs / K of Spades / 4 of Diamonds / J of Diamond
s / Q of Spades / A of Diamonds / K of Clubs / 4 of Hearts / T of Spades / 9 of
Hearts / 6 of Clubs / A of Hearts / 8 of Clubs / Q of Clubs / 9 of Clubs / T of
Clubs / 6 of Hearts / 6 of Hearts / K of Diamonds / 2 of Clubs / 5 of Diamonds /
Q of Hearts / Q of Diamonds / A of Diamonds / 5 of Diamonds / 2 of Spades / 7 o
f Clubs / 9 of Diamonds / 6 of Diamonds / 7 of Spades / 4 of Clubs / 9 of Diamon
ds / 9 of Spades / A of Spades / 7 of Hearts / 2 of Hearts / J of Clubs / 8 of C
lubs / A of Clubs / 4 of Spades / K of Diamonds / T of Spades / T of Diamonds /
Q of Diamonds / K of Hearts / 4 of Hearts / 6 of Diamonds / J of Hearts / 6 of S
pades / 8 of Spades / 7 of Diamonds / 8 of Diamonds / 2 of Diamonds / 8 of Heart
s / K of Hearts / 5 of Spades / K of Clubs / 4 of Spades / J of Hearts / 9 of Sp
ades / 3 of Hearts / K of Spades / 4 of Clubs / 9 of Hearts / 6 of Clubs / 7 of
Diamonds / A of Hearts / 2 of Spades / J of Spades / J of Spades / T of Hearts /
5 of Spades / 7 of Hearts / J of Diamonds / 5 of Hearts / 3 of Spades / 4 of Di
amonds / 2 of Clubs / 8 of Hearts / 2 of Diamonds / 3 of Diamonds / 7 of Clubs /
8 of Spades / 5 of Hearts / 9 of Clubs /

K of Spades / Q of Spades / J of Spades / T of Spades / 9 of Spades / 8 of
Spades / 7 of Spades / 6 of Spades / 5 of Spades / 4 of Spades / 3 of Spade
s / 2 of Spades / A of Spades / K of Hearts / Q of Hearts / J of Hearts /
T of Hearts / 9 of Hearts / 8 of Hearts / 7 of Hearts / 6 of Hearts / 5 of
Hearts / 4 of Hearts / 3 of Hearts / 2 of Hearts / A of Hearts / K of Diamo
nds / Q of Diamonds / J of Diamonds / T of Diamonds / 9 of Diamonds / 8 of
Diamonds / 7 of Diamonds / 6 of Diamonds / 5 of Diamonds / 4 of Diamonds /
3 of Diamonds / 2 of Diamonds / A of Diamonds / K of Clubs / Q of Clubs / J
of Clubs / T of Clubs / 9 of Clubs / 8 of Clubs / 7 of Clubs / 6 of Clubs
/ 5 of Clubs / 4 of Clubs / 3 of Clubs / 2 of Clubs / A of Clubs /

2 of Hearts / 3 of Diamonds / 3 of Clubs / 4 of Diamonds / Q of Diamonds /
2 of Spades / 3 of Hearts / K of Hearts / 6 of Clubs / K of Spades / 4 of C
lubs / 6 of Spades / 8 of Diamonds / 5 of Clubs / 9 of Diamonds / 5 of Diam
onds / 3 of Spades / K of Clubs / J of Diamonds / A of Diamonds / Q of Spad
es / T of Hearts / J of Hearts / A of Hearts / J of Clubs / 7 of Spades /
6 of Diamonds / 9 of Hearts / 8 of Clubs / K of Diamonds / 7 of Clubs / 7 o
f Diamonds / 8 of Spades / 4 of Spades / 2 of Diamonds / 5 of Hearts / 9 of
Spades / T of Spades / 2 of Clubs / 5 of Spades / 6 of Hearts / Q of Clubs
/ 4 of Hearts / A of Spades / 9 of Clubs / J of Spades / T of Clubs / A o
f Clubs / Q of Hearts / T of Diamonds / 7 of Hearts / 8 of Hearts /

Press any key to continue . . .
--------------------------------------------------------- */
Phase 2: The Deck and Hand Classes

For your second test client, allow your Deck class to interact with your Hand class. Don't add anything to the two classes, but do everything in this phase from within your main() client.

Ask the user (interactively) to select the number of players (a number from 1 to 10). That's one question, one numeric answer, and no further user-interaction. Once you have a legal value, instantiate a single-pack Deck object without shuffling, deal a deck into that many Hand objects, dealing all cards until the deck is empty. Since the number of players chosen by the user may not divide evenly into 52, the number of cards dealt into the various hands might differ, but only by, at most, one. Display all the hands after the deal.

Reset the objects to their initial state, but this time shuffle the deck before a second deal (same # of players).

To be clear, dealing to hands means dealing a single card to each hand, until all hands have one card, then repeating to give all hands a second card, etc., until the cards are gone, and each hand has (nearly) the same number of cards. It does not mean dealing x cards to one hand, then x to the next hand, etc. This is very important.

You don't need any more classes than the ones we've already created, since there should not be that much to do in main().

Example of One of Possibly Many Test Runs of Deck + Card Classes

--------------- run #2 ----------------------------------

How many hands? (1 - 10, please): 6
Here are our hands, from unshuffled deck:
Hand = ( K of Spades, 7 of Spades, A of Spades, 8 of Hearts, 2 of Hearts, 9 of
Diamonds, 3 of Diamonds, T of Clubs, 4 of Clubs )

Hand = ( Q of Spades, 6 of Spades, K of Hearts, 7 of Hearts, A of Hearts, 8 of
Diamonds, 2 of Diamonds, 9 of Clubs, 3 of Clubs )

Hand = ( J of Spades, 5 of Spades, Q of Hearts, 6 of Hearts, K of Diamonds, 7 o
f Diamonds, A of Diamonds, 8 of Clubs, 2 of Clubs )

Hand = ( T of Spades, 4 of Spades, J of Hearts, 5 of Hearts, Q of Diamonds, 6 o
f Diamonds, K of Clubs, 7 of Clubs, A of Clubs )

Hand = ( 9 of Spades, 3 of Spades, T of Hearts, 4 of Hearts, J of Diamonds, 5 o
f Diamonds, Q of Clubs, 6 of Clubs )

Hand = ( 8 of Spades, 2 of Spades, 9 of Hearts, 3 of Hearts, T of Diamonds, 4 o
f Diamonds, J of Clubs, 5 of Clubs )

Here are our hands, from SHUFFLED deck:
Hand = ( 9 of Clubs, Q of Spades, 8 of Hearts, Q of Hearts, 3 of Hearts, 9 of S
pades, K of Hearts, 8 of Spades, T of Diamonds )

Hand = ( T of Clubs, 5 of Spades, 3 of Clubs, A of Diamonds, K of Clubs, 5 of H
earts, J of Diamonds, 7 of Diamonds, 2 of Spades )

Hand = ( 4 of Spades, 2 of Clubs, Q of Diamonds, 8 of Clubs, 4 of Hearts, 2 of
Hearts, 3 of Spades, 2 of Diamonds, J of Clubs )

Hand = ( 9 of Hearts, 4 of Diamonds, T of Hearts, 4 of Clubs, 5 of Diamonds, 7
of Clubs, A of Clubs, 7 of Spades, A of Hearts )

Hand = ( J of Spades, 6 of Diamonds, 9 of Diamonds, 5 of Clubs, 6 of Spades, J
of Hearts, 8 of Diamonds, K of Diamonds )

Hand = ( Q of Clubs, T of Spades, 3 of Diamonds, 6 of Hearts, 6 of Clubs, 7 of
Hearts, K of Spades, A of Spades )

Press any key to continue . . .
--------------------------------------------------------- */
For this part, you will be graded on how efficiently you put together these two classes. Use what you know about arrays, loops, the methods available in the Deck and Hand classes to give a clean, short and completely tested client that proves that your Deck can feed the number of Hands requested by the user. There is some amount of creativity and variability allowed in this part, and any two correct solutions will look very different. You can implement this in any way that interprets the instructions. Yet, I can and will deduct when I see basic programming concepts misused, deduction amounts commensurate with the type of infraction.

  • asdf.txt This attachment has been locked.

Sam responded:

This will help :)

#include <iostream>
using namespace std;

int main(){
int deck[52]={7,4,13,11,13,6,13,12,11,1,13,5,1,8,3,6,4,12,2,9,8,7,10,7,7,3,1,10,10,6,8,9,12,2,11,5,12,5,3,8,10,9,11,1,4,9,2,3,4,6,2,5};
int prev=0, current=deck[0];
int player1[5];
int player2[5];
int player3[5];
int player4[5];

for(int p1_assign=0; p1_assign<5; p1_assign++){
player1[p1_assign]=deck[p1_assign+1];
}
int i=6;
for(int p2_assign=0; p2_assign<5; p2_assign++){
player2[p2_assign]=deck[i];
i++;
}
int w=11;
for(int p3_assign=0; p3_assign<5; p3_assign++){
player3[p3_assign]=deck[w];
w++;
}
int t=16;
for(int p4_assign=0; p4_assign<5; p4_assign++){
player4[p4_assign]=deck[t];
t++;
}
int temp=0;

for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player1[j]>player1[j+1]){
temp=player1[j];
player1[j]=player1[j+1];
player1[j+1]=temp;
}
}
}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player2[j]>player2[j+1]){
temp=player2[j];
player2[j]=player2[j+1];
player2[j+1]=temp;
}
}
}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player3[j]>player3[j+1]){
temp=player3[j];
player3[j]=player3[j+1];
player3[j+1]=temp;
}
}
}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player4[j]>player4[j+1]){
temp=player4[j];
player4[j]=player4[j+1];
player4[j+1]=temp;
}

}
}
for(int i=0; i<5; i++){
cout<<player1[i]<<endl;
}
for(int i=0; i<5; i++){
cout<<player2[i]<<endl;
}
for(int i=0; i<5; i++){
cout<<player3[i]<<endl;
}
for(int i=0; i<5; i++){
cout<<player4[i]<<endl;
}

int end_deck=21;
while (end_deck<=51){
if (deck[end_deck]<player1[5]){
current=player1[5];
player1[5]=deck[end_deck];
end_deck++;
}
else if(current<player1[5]){
prev=player1[5];
player1[5]=current;
current=prev;

}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player1[j]>player1[j+1]){
temp=player1[j];
player1[j]=player1[j+1];
player1[j+1]=temp;
}
}
}

if (deck[end_deck]<player2[5]){
current=player2[5];
player2[5]=deck[end_deck];
end_deck++;
}
else if (current<player2[5]){
prev=player2[5];
player2[5]=current;
current=prev;
}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player2[j]>player2[j+1]){
temp=player2[j];
player2[j]=player2[j+1];
player2[j+1]=temp;
}
}
}
if (deck[end_deck]<player3[5]){
current=player3[5];
player3[5]=deck[end_deck];
end_deck++;
}
else if (current<player3[5]){
prev=player3[5];
player3[5]=current;
current=prev;
}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player3[j]>player3[j+1]){
temp=player3[j];
player3[j]=player3[j+1];
player3[j+1]=temp;
}
}
}
if (deck[end_deck]<player4[5]){
current=player4[5];
player4[5]=deck[end_deck];
end_deck++;
}
else if (current<player4[5]){
prev=player4[5];
player4[5]=current;
current=prev;
}
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(player4[j]>player4[j+1]){
temp=player4[j];
player4[j]=player4[j+1];
player4[j+1]=temp;
}
}
}
}

int sum1=0,sum2=0,sum3=0,sum4=0, least=1;
for (int i=0; i<5; i++){
sum1=sum1+player1[i];
}
for (int i=0; i<5; i++){
sum2=sum2+player1[i];
}
for (int i=0; i<5; i++){
sum3=sum3+player1[i];
}
for (int i=0; i<5; i++){
sum4=sum4+player1[i];
}

if(sum1<sum2){
if(sum1<sum3){
if(sum1<sum4){
least=1;
}
}
}
else if(sum2<sum1){
if(sum2<sum3){
if(sum2<sum4){
least=2;
}
}
}
else if(sum3<sum1){
if(sum1<sum2){
if(sum1<sum4){
least=3;
}
}
}
else if(sum4<sum1){
if(sum1<sum2){
if(sum1<sum3){
least=4;
}
}
}

if(least==1)
cout<<"Player1 wins \n";
else if(least==2)
cout<<"Player2 wins \n";
else if(least==3)
cout<<"Player3 wins \n";
else if(least==4)
cout<<"Player4 wins \n";

}

Feedback:

Subject: Pre-Calculus

Someone asked:

graph the relation defined by the parametric equations: x=3-t^2 and y=1+2t for -3<t<3

*note that the signs should be less than or equal to but i couldnt do that on my computer

PLEASE SHOW ALL WORK THANK YOU!

Sam responded:

From the given equation x = 3 - t^2 you can find the value of t:
here:
t = sqrt( 3 - x)
then plug in that value in equation 2 wich is y = ......
you get:
y = 1 + 2* sqrt(3-x)

you can use ur calculator to graph this. but to give you a hint in what u will get. it will be a graph of the square root shifted up by 1 and to the right by 3 after it was reflected around the y accesss :)

thanks

Subject: C++ Programming

Someone asked:

Understand the Class and Problem

We continue to work on the card game effort, now adding the source of all cards for the various players, the Deck.

Deck: A class that represents the source of the cards for dealing and, as the game progresses, the place from which players can receive new cards (say, as they pick cards "from the deck" or when future hands are to be dealt from the same deck). Recall this picture, which relates the Deck to the various Hands that it creates through the process called "dealing":
pic of dealing

Let's deconstruct the meaning of this important class.

Deck: A Deck object is the source of all cards. It's where the dealer gets cards to deal, and if a player takes an individual card after the deal, he takes it from the Deck object. Naturally, the primary member here is an array of Card objects, much like Hand. We'll call this member cards[]. A deck normally consists of a single pack of cards: 52 cards (four suits of 13 values each). However, some games use two, three or more packs. If a card game requires two packs, then the deck will consist of two full 52-card packs: 104 cards. (Many games throw away some cards before beginning. For example Pinochle wants all cards with values 8-and-below to be taken out of the deck, but we will not trouble ourselves with this complexity.) A newly instantiated deck will have a multiple of 52 cards and will contain all the standard cards, so the number of cards in a newly instantiated deck will be 52, 104, 156, ..., i.e., numPacks × 52.

Clearly, we need an int like Hand's numCards, to keep track of how many cards are actually in the cards[] array. To this end, we'll use topCard (not numCards), since a deck typically removes and delivers cards to players from the top-of-the-deck, and this is a convenient variable to use for the number of cards as well as the position of the top of the deck.

There are a few other useful members (numPacks, for example). In addition to the the usual constructors and accessors, we'll want a dealCard() to return and remove the card at the top of the deck (which may be received by a client and added to some player's hand), and a shuffle() to re-order the cards in a random fashion. Also, we'll need to restock the deck (init()) to the original full condition in preparation for a fresh deal (we would certainly not want to re-instantiate a new deck when we have a perfectly good one available: garbage collection, done by us or by the operating system, is a resource we do not abuse).

Phase 1: The Deck Class

Public Static Class Constants

Define a public int value like MAX_CARDS, and initialize it to allow a maximum of six packs (6×52 cards).

Private Static Member Data

card masterPack[52]
This is a public static Card array, masterPack[], containing exactly 52 card objects, which includes all the standard cards. It will enable us to avoid capriciously and repeatedly declaring the same 52 cards which are needed as the game proceeds. In other words, once we have, say, a ('6', spades) Card constructed and stored (inside this masterPack[]), we use that same instance whenever we need it as a source to copy in various places, notably during a re-initialization of the Deck object; it will always be in the masterPack[] array for us to copy.

Private Member Data

Card cards[...];
int topCard;
int numPacks;
Public Methods

Deck(int numPacks = 1) - a constructor that populates the arrays and assigns initial values to members.
void init(int numPacks = 1) - re-populate cards[] with the standard 52 × numPacks cards. We should not repopulate the static array, masterPack[], since that was done once, in the (first-invoked) constructor and never changes.
void shuffle() - mixes up the cards with the help of the standard random number generator.
Card dealCard() - returns and removes the card in the top occupied position of cards[].
An accessor for the int, topCard (no mutator.)
Card inspectCard(int k) - Accessor for an individual card. Returns a card with errorFlag = true if k is bad.
Private Methods

static void allocateMasterPack() - this is a method that will be called by the constructor. However, it has to be done with a very simple twist: even if many Deck objects are constructed in a given program, this static method will not allow itself to be executed more than once. Since masterPack[] is a static, unchanging, entity, it need not be built every time a new Deck is instantiated. So this method needs to be able to ask itself, "Have I been here before?", and if the answer is "yes", it will immediately return without doing anything; it has already built masterPack[] in a previous invocation.
Recommended test of Class Deck

Declare a deck containing two packs of cards. Do not shuffle. Deal all the cards in a loop until the deck is empty (dealt directly to the display/screen, not to any Hand objects just yet). Display each card as it comes off the deck. Next, reset the deck by initializing it again (to the same two packs). Shuffle the deck this time, and re-deal to the screen in a loop again. Notice that the cards are now coming off in a random order.

Repeat this double deal, unshuffled, then shuffled, but this time using a single pack deck.

Example Test Run of Card Class

/* ---------------------------------------------------------
K of Spades / Q of Spades / J of Spades / T of Spades / 9 of Spades / 8 of
Spades / 7 of Spades / 6 of Spades / 5 of Spades / 4 of Spades / 3 of Spade
s / 2 of Spades / A of Spades / K of Hearts / Q of Hearts / J of Hearts /
T of Hearts / 9 of Hearts / 8 of Hearts / 7 of Hearts / 6 of Hearts / 5 of
Hearts / 4 of Hearts / 3 of Hearts / 2 of Hearts / A of Hearts / K of Diamo
nds / Q of Diamonds / J of Diamonds / T of Diamonds / 9 of Diamonds / 8 of
Diamonds / 7 of Diamonds / 6 of Diamonds / 5 of Diamonds / 4 of Diamonds /
3 of Diamonds / 2 of Diamonds / A of Diamonds / K of Clubs / Q of Clubs / J
of Clubs / T of Clubs / 9 of Clubs / 8 of Clubs / 7 of Clubs / 6 of Clubs
/ 5 of Clubs / 4 of Clubs / 3 of Clubs / 2 of Clubs / A of Clubs / K of Sp
ades / Q of Spades / J of Spades / T of Spades / 9 of Spades / 8 of Spades
/ 7 of Spades / 6 of Spades / 5 of Spades / 4 of Spades / 3 of Spades / 2
of Spades / A of Spades / K of Hearts / Q of Hearts / J of Hearts / T of He
arts / 9 of Hearts / 8 of Hearts / 7 of Hearts / 6 of Hearts / 5 of Hearts
/ 4 of Hearts / 3 of Hearts / 2 of Hearts / A of Hearts / K of Diamonds /
Q of Diamonds / J of Diamonds / T of Diamonds / 9 of Diamonds / 8 of Diamond
s / 7 of Diamonds / 6 of Diamonds / 5 of Diamonds / 4 of Diamonds / 3 of Di
amonds / 2 of Diamonds / A of Diamonds / K of Clubs / Q of Clubs / J of Clu
bs / T of Clubs / 9 of Clubs / 8 of Clubs / 7 of Clubs / 6 of Clubs / 5 of
Clubs / 4 of Clubs / 3 of Clubs / 2 of Clubs / A of Clubs /

T of Hearts / T of Diamonds / A of Clubs / Q of Spades / 3 of Clubs / 8 of Diamo
nds / T of Clubs / 5 of Clubs / J of Clubs / 3 of Clubs / 3 of Diamonds / 3 of H
earts / 3 of Spades / 2 of Hearts / Q of Clubs / 7 of Spades / A of Spades / Q o
f Hearts / 6 of Spades / 5 of Clubs / K of Spades / 4 of Diamonds / J of Diamond
s / Q of Spades / A of Diamonds / K of Clubs / 4 of Hearts / T of Spades / 9 of
Hearts / 6 of Clubs / A of Hearts / 8 of Clubs / Q of Clubs / 9 of Clubs / T of
Clubs / 6 of Hearts / 6 of Hearts / K of Diamonds / 2 of Clubs / 5 of Diamonds /
Q of Hearts / Q of Diamonds / A of Diamonds / 5 of Diamonds / 2 of Spades / 7 o
f Clubs / 9 of Diamonds / 6 of Diamonds / 7 of Spades / 4 of Clubs / 9 of Diamon
ds / 9 of Spades / A of Spades / 7 of Hearts / 2 of Hearts / J of Clubs / 8 of C
lubs / A of Clubs / 4 of Spades / K of Diamonds / T of Spades / T of Diamonds /
Q of Diamonds / K of Hearts / 4 of Hearts / 6 of Diamonds / J of Hearts / 6 of S
pades / 8 of Spades / 7 of Diamonds / 8 of Diamonds / 2 of Diamonds / 8 of Heart
s / K of Hearts / 5 of Spades / K of Clubs / 4 of Spades / J of Hearts / 9 of Sp
ades / 3 of Hearts / K of Spades / 4 of Clubs / 9 of Hearts / 6 of Clubs / 7 of
Diamonds / A of Hearts / 2 of Spades / J of Spades / J of Spades / T of Hearts /
5 of Spades / 7 of Hearts / J of Diamonds / 5 of Hearts / 3 of Spades / 4 of Di
amonds / 2 of Clubs / 8 of Hearts / 2 of Diamonds / 3 of Diamonds / 7 of Clubs /
8 of Spades / 5 of Hearts / 9 of Clubs /

K of Spades / Q of Spades / J of Spades / T of Spades / 9 of Spades / 8 of
Spades / 7 of Spades / 6 of Spades / 5 of Spades / 4 of Spades / 3 of Spade
s / 2 of Spades / A of Spades / K of Hearts / Q of Hearts / J of Hearts /
T of Hearts / 9 of Hearts / 8 of Hearts / 7 of Hearts / 6 of Hearts / 5 of
Hearts / 4 of Hearts / 3 of Hearts / 2 of Hearts / A of Hearts / K of Diamo
nds / Q of Diamonds / J of Diamonds / T of Diamonds / 9 of Diamonds / 8 of
Diamonds / 7 of Diamonds / 6 of Diamonds / 5 of Diamonds / 4 of Diamonds /
3 of Diamonds / 2 of Diamonds / A of Diamonds / K of Clubs / Q of Clubs / J
of Clubs / T of Clubs / 9 of Clubs / 8 of Clubs / 7 of Clubs / 6 of Clubs
/ 5 of Clubs / 4 of Clubs / 3 of Clubs / 2 of Clubs / A of Clubs /

2 of Hearts / 3 of Diamonds / 3 of Clubs / 4 of Diamonds / Q of Diamonds /
2 of Spades / 3 of Hearts / K of Hearts / 6 of Clubs / K of Spades / 4 of C
lubs / 6 of Spades / 8 of Diamonds / 5 of Clubs / 9 of Diamonds / 5 of Diam
onds / 3 of Spades / K of Clubs / J of Diamonds / A of Diamonds / Q of Spad
es / T of Hearts / J of Hearts / A of Hearts / J of Clubs / 7 of Spades /
6 of Diamonds / 9 of Hearts / 8 of Clubs / K of Diamonds / 7 of Clubs / 7 o
f Diamonds / 8 of Spades / 4 of Spades / 2 of Diamonds / 5 of Hearts / 9 of
Spades / T of Spades / 2 of Clubs / 5 of Spades / 6 of Hearts / Q of Clubs
/ 4 of Hearts / A of Spades / 9 of Clubs / J of Spades / T of Clubs / A o
f Clubs / Q of Hearts / T of Diamonds / 7 of Hearts / 8 of Hearts /

Press any key to continue . . .
--------------------------------------------------------- */
Phase 2: The Deck and Hand Classes

For your second test client, allow your Deck class to interact with your Hand class. Don't add anything to the two classes, but do everything in this phase from within your main() client.

Ask the user (interactively) to select the number of players (a number from 1 to 10). That's one question, one numeric answer, and no further user-interaction. Once you have a legal value, instantiate a single-pack Deck object without shuffling, deal a deck into that many Hand objects, dealing all cards until the deck is empty. Since the number of players chosen by the user may not divide evenly into 52, the number of cards dealt into the various hands might differ, but only by, at most, one. Display all the hands after the deal.

Reset the objects to their initial state, but this time shuffle the deck before a second deal (same # of players).

To be clear, dealing to hands means dealing a single card to each hand, until all hands have one card, then repeating to give all hands a second card, etc., until the cards are gone, and each hand has (nearly) the same number of cards. It does not mean dealing x cards to one hand, then x to the next hand, etc. This is very important.

You don't need any more classes than the ones we've already created, since there should not be that much to do in main().

Example of One of Possibly Many Test Runs of Deck + Card Classes

--------------- run #2 ----------------------------------

How many hands? (1 - 10, please): 6
Here are our hands, from unshuffled deck:
Hand = ( K of Spades, 7 of Spades, A of Spades, 8 of Hearts, 2 of Hearts, 9 of
Diamonds, 3 of Diamonds, T of Clubs, 4 of Clubs )

Hand = ( Q of Spades, 6 of Spades, K of Hearts, 7 of Hearts, A of Hearts, 8 of
Diamonds, 2 of Diamonds, 9 of Clubs, 3 of Clubs )

Hand = ( J of Spades, 5 of Spades, Q of Hearts, 6 of Hearts, K of Diamonds, 7 o
f Diamonds, A of Diamonds, 8 of Clubs, 2 of Clubs )

Hand = ( T of Spades, 4 of Spades, J of Hearts, 5 of Hearts, Q of Diamonds, 6 o
f Diamonds, K of Clubs, 7 of Clubs, A of Clubs )

Hand = ( 9 of Spades, 3 of Spades, T of Hearts, 4 of Hearts, J of Diamonds, 5 o
f Diamonds, Q of Clubs, 6 of Clubs )

Hand = ( 8 of Spades, 2 of Spades, 9 of Hearts, 3 of Hearts, T of Diamonds, 4 o
f Diamonds, J of Clubs, 5 of Clubs )

Here are our hands, from SHUFFLED deck:
Hand = ( 9 of Clubs, Q of Spades, 8 of Hearts, Q of Hearts, 3 of Hearts, 9 of S
pades, K of Hearts, 8 of Spades, T of Diamonds )

Hand = ( T of Clubs, 5 of Spades, 3 of Clubs, A of Diamonds, K of Clubs, 5 of H
earts, J of Diamonds, 7 of Diamonds, 2 of Spades )

Hand = ( 4 of Spades, 2 of Clubs, Q of Diamonds, 8 of Clubs, 4 of Hearts, 2 of
Hearts, 3 of Spades, 2 of Diamonds, J of Clubs )

Hand = ( 9 of Hearts, 4 of Diamonds, T of Hearts, 4 of Clubs, 5 of Diamonds, 7
of Clubs, A of Clubs, 7 of Spades, A of Hearts )

Hand = ( J of Spades, 6 of Diamonds, 9 of Diamonds, 5 of Clubs, 6 of Spades, J
of Hearts, 8 of Diamonds, K of Diamonds )

Hand = ( Q of Clubs, T of Spades, 3 of Diamonds, 6 of Hearts, 6 of Clubs, 7 of
Hearts, K of Spades, A of Spades )

Press any key to continue . . .
--------------------------------------------------------- */
For this part, you will be graded on how efficiently you put together these two classes. Use what you know about arrays, loops, the methods available in the Deck and Hand classes -- even testing user input for valid in-range response -- to give a clean, short and completely tested client that proves that your Deck can feed the number of Hands requested by the user. There is some amount of creativity and variability allowed in this part, and any two correct solutions will look very different. You can implement this in any way that interprets the instructions. Yet, I can and will deduct when I see basic programming concepts misused, deduction amounts commensurate with the type of infraction.

Sam responded:

//These examples will help you//

class PlayerCard
{
private:
int _suit;
int _number;
public:
PlayerCard(void);
~PlayerCard(void);
void setSuit(int x) {_suit = x;}
int getSuit() {return _suit;}
void setNumber(int x) {_number = x;}
int getNumber() {return _number;}
};

//_________________________________//

class Player
{
private:
vector _hand;
public:
Player(void);
~Player(void);
void addCardtoHand(Card card);
Card removeCardfromHand(int x);
void displayHand();
int getHandSize() { return _hand.size(); }
};

Player::Player(void)
{
cout << "Construct the Player" << endl;
}

Player::~Player(void)
{
}

void Player::displayHand()
{
cout << "Display Hand" << endl;
for(unsigned int i = 0; i < _hand.size(); i++)
{
cout << "Suit: " << _hand[i].getSuit() << " Number: "<< _hand[i].getNumber() << endl;
}
}

void Player::addCardtoHand(Card card)
{
_hand.push_back(card);
}

Card Player::removeCardfromHand(int x)
{
Card temp = _hand[x];
_hand.erase(_hand.begin() + x);
return temp;
}

//---------------------------------------------//

#include "Card.hpp"
#include <algorithm>
using namespace std;

class Deck
{
private:
vector _deck;
public:
void initialiseDeck();
void displayDeck();
void shuffleDeck();
void addCard(Card card);
Card removeTopCard();
int getSize() {return _deck.size();}

Deck(void);
~Deck(void);
};

Deck::Deck(void)
{
Card temp;
//Create a deck with 52 cards
for(int i = 0; i < 52; i++)
{
_deck.push_back(temp);
}
}

Deck::~Deck(void)
{
}

void Deck::initialiseDeck()
{
int num = 0;
int type = 0;

for(unsigned int i = 0; i < _deck.size(); i++) { if(num > 12)
{
num = 0;
type++;
}

_deck[i].setNumber(num + 1);
_deck[i].setSuit(type);

num++;
}
}

void Deck::displayDeck()
{
for(unsigned int i = 0; i < _deck.size(); i++)
{
cout << "Suit: " << _deck[i].getSuit() << " Number: " << _deck[i].getNumber() << endl;
}
}

void Deck::shuffleDeck()
{
random_shuffle(_deck.begin(), _deck.end());
}

Card Deck::removeTopCard()
{
Card temp = _deck[_deck.size() - 1];
_deck.pop_back();
return temp;
}

void Deck::addCard(Card card)
{
_deck.push_back(card);
}</algorithm>

int main()
{
Deck _deck;
Player _player;

//Initialise Deck, and Shuffle it
_deck.initialiseDeck();
_deck.shuffleDeck();

//Remove the top card from the deck and add it to the player's hand
_player.addCardtoHand(_deck.removeTopCard());
_player.displayHand();
}

Feedback:

Subject: Chemistry

Someone asked:

2) Our atmisphere can be characterized both as a thin veil that supports life and as a few vertical miles of chemicals. Explain what makes each description accurate. Also state which features of our atmosphere each description emphazised and which ones it omits ?
6) a)The concentration of argon in air is appoximately 0.9%. Express this value in ppm.
b) The air exhaled from the lungs of a smoker has a concentration of 20-50ppm CO. In contrast, air exhaled by nonsmokers is 0-2 ppm CO. Express each concentration as a percent.
c) In a tropical rain forest, the water vapor concentration may reach 50,000ppm. Express this as a percent.
d) In the dry polar regions, water vapor may be a mere 10ppm. Express this a percent.

8) Consider this representation of the reaction between nitrogen and hydrogen to form ammonia (NH3) [3a image as attached]
a) Are the masses of reactants and products the same? Explain.
b) Are the nmbers of molecules of reactants and of products the same? Explain.
c) Are the total number of atoms in the reactants and the total number of atoms in the products the same? explain.

12b) This fire is emitting at least three pollutants. Which are visible and which are not?

23a ) Count the atoms on both sides of the arrow to demonstrate that these equations are balanced.
2 C3H8 (g) + 7 02(g) === 6 CO (g) + 8 H20 (l)

29) The percentage of carbon dioxide in inhaled air is lower than it is in exhaled air, but the percentage of oxygen in inhaled air is higher than in exhaled air. How an you account for these relationships?

30 Cars don't in hale and exhale like humans do Nonetheless, the air that goes into a car is different from what comes out. In Your Turn 1.19 you listed what comes out a tailpipe. Now comment on the differences between the air that goes into the car engine and what comes out the tailpipe. For which chemicals have the concentrations noticeable increased or decreased ?

32) A headline from the Pioneer Press in St. Paul Minnesota (January 8, 2008) : " Man dies after exposure to gas; carbon monoxide sickens five others"
a) name two possible sources of CO inside a home.
b) The level measured was 4700 ppm. Express this value as a percent.
c) How does this level compare with the US ambient air quality standards set by the EPA?
d) Name three symptoms that the survivors most likely experienced.
e) Where in a home should you install CO detectors? Note : adjacent to a furnace is not usually recommended.

44) At certain times of the year, inhabitants of the beautiful city of Santiago, Chile, breathe some of the worst air on the planet ?

45) Explain why jogging outdoors ( as opposed to sitting outdoors) increases your exposure to pollutants.
b ) Jogging indoors at home can decrease your exposure to some pollutants, but may increase your exposure to others. Explain.

Sam responded:

Earth atmosphere behave as thin veil which support the life on earth because it contains four layers in atmosphere. from outer space first thermosphere second mesosphere third stratosphere and last one which close to the earth is tropospere.
The stratosphere contains the ozone layer which protects the earth life from the UV rays.

And they also behave as the chemical miles because in the trosphere contain some gases like water vapoer, carbon, dioxide and methane as major parts. it is near about 10 km in hight so it makes suitable space for life in earth.

in case of stratosphere its hhight near about 50 km which contain ozone CFCs, HCFCs oxygen gas which protect earth life by their ozone layer.
The mesosphere hight is about 80 km which contain some gases which trap some high frequency radiations and ultrviolet radiation.
thermosphere is the hightest leavel from earth so it contains low concentration of gases due to high temperature.

45) Jogging outdoors, as opposed to sitting outdoors, increases your exposure to air pollutants because you
will be breathing harder and exchanging more air during your exercise.

Subject: Java Programming

Someone asked:

Hello, I am having a little bit of trouble understanding queues and how they work. Could anyone give me a detailed explanation of how they work, their methods, and some example code instantiating queues using java 7 methods and below. I know there is add() and remove() however their might be more. Could you please clarify and/or add as much information to this as you can. Thanks

Sam responded:

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue; // import the Queue to be able to use it :)

/*first off, in order to be able to use Queue. You need to import java.util.Queue*/

public class QueueExample {

public static void main(String[] args) {

// Here we will creat a Queue that will hold Strings ( texts).

Queue<String> qe = new LinkedList<String>(); // This you have to memorize ( I mean the way you creat a new Object of Queue).

qe.add("b");// This will add string "b" to the Queue that we created which is called qe as you can see we use <the name of the Queue that we created>.add("something").
qe.add("a");// We do the samething here but we add "a"
qe.add("c");// then we add "c"
qe.add("e");// then we add "e"
qe.add("d");// then we add "d".

Iterator it=qe.iterator(); // Iterators are used to print out all the values of the Queue that we created. This is what you do. you first do this line.

System.out.println("Initial Size of Queue :"+qe.size()); // this is just to print out the number of elements that we strored in qe which is the Queue that we created


// then you use a while loop to print all elements. Here we are saying that while the Queue that we created still has elements as we move a long. keep going
// and stop when there is no more elmements to print.
// you use the ".hasNext() method which is from Java :):

while(it.hasNext())
{

String iteratorValue=(String)it.next();
System.out.println("Queue Next Value :"+iteratorValue); // the printing of each one is done here. Since Queue are first in first out we will see "b" print first.
}

// peek () method gets the value for us and here we print it out. get value and does not remove element from queue or do anything ot the queue.

System.out.println("Queue peek :"+qe.peek());

//But poll will get that value that we added first then pops it out;so now we have a new first value get first value and remove that object from queue

System.out.println("Queue poll :"+qe.poll());

// I printed this to show you that after using the poll() method we will lose an element and the size is no longer 5 :)
System.out.println("Final Size of Queue :"+qe.size());
}

things to understand:

1)Queue is First in first out. It's like stacking a stack of books then removing the bottom one first and then removing second and so on.....
2) poll() method will remove the element that was added first and will store that value if we have something like this : String s = eq.poll() it will stroe it in s :)
3) peek() method does the same thing but it does not remove that value. it only stores it in s (i.e it peeks at it :))

Subject: Computer Science

Someone asked:

R programming

Sam responded:

I can help :)

Subject: Electrical Engineering

InstaEDU asked:

What is Electrical Engineering?

Sam responded:

Engineering that deals with the software part of devices that we see around. It has different fields such as electric circuits,signal processing, or signals and systems.


Subject: Java Programming

InstaEDU asked:

What is Java Programming?

Sam responded:

java is an object oriented programing language unlike C and other older computer languages object oriented languages have the ability to create instances of objects.


Subject: Arabic

InstaEDU asked:

What is Arabic?

Sam responded:

An old language that is spoken by more than 22 countries around the world.


Subject: Engineering and Technology

InstaEDU asked:

Why study Engineering and Technology?

Sam responded:

Engineers are best at solving problems that we face everyday and to make our lives easier.


Subject: C Sharp Programming

InstaEDU asked:

Why study C Sharp Programming?

Sam responded:

C sharp is a really great easy language to finish programing tasks.


Subject: Advanced College Math

InstaEDU asked:

Why study Advanced College Math?

Sam responded:

Because it's really fun to see how things work and make sense after understanding the subject.

You have blocked Sam. To unblock them Click Here

Send Sam a Message

TIP: Want to set up a lesson? Include a description of what you're working on and when you'd like to meet.

          By sending a message, you agree to our
          Terms of Service and Privacy Policy.
          • Likelihood of Reply: < 20%
          • Expected Response Time: 2 hours

          Frequently Asked Questions

          + How do lessons work?

          You and your tutor will meet in an online lesson space. You'll have access to video, audio and text chat and be able to upload documents, draw on a chalkboard and edit papers in real time.

          + Who are InstaEDU's tutors?

          Many InstaEDU tutors are current students or recent graduates of top-tier colleges like Harvard, Stanford and MIT. InstaEDU has thousands of tutors available to work with you on your toughest assignments.

          + How much does tutoring cost?

          New students can try InstaEDU for free, and additional lessons are as little as $24/hour, depending on how frequently you think you'll want to meet with a tutor

          + How do I set up my first lesson?

          Just use the the form above to send a message and schedule your first lesson!