I am trying to write a program that determines the smaller and greater value based on user input. But I am not sure how to do this. The integer values are stored into variables named val1 and val2. So the user enters a value into each of the variables, and I want the program to determine what is the smaller and larger number.
This is what my code currently looks like:
int main()
{
int val1;
int val2;
cout<< "enter an integer followed by enter twice,\n";
cin>> val1 >> val2;
}
}
I think this is what you are looking for :
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, big;
cout<<"Enter two number : ";
cin>>a>>b;
if(a>b)
{
big=a;
}
else
{
big=b;
}
cout<<"Biggest of the two number is "<<big;
getch();
}
Another way of finding the greater value.
#include<conio.h>
void main()
{
clrscr();
int a, b, big;
cout<<"Enter two number : ";
cin>>a>>b;
cout<<"Biggest of the two number is "<<a>b?a:b; // ternary operator is used instead of checking with if condition.
getch();
}
You can also try to use std::max (http://www.cplusplus.com/reference/algorithm/max/).
Related
Write a program using stack operations, which accepts a non-negative base 10 integer as a parameter, and display binary representation of number. I am getting error in my main that been trying to understand but no success so far , rest all the logic works but adding the remainder (node r) function is primarily the issue
and code is :
# include<iostream>
using namespace std;
class ListStack{
private:
struct node
{
int num;
node *next;
}*top;
public:
ListStack()
{
top= NULL;
}
void push(node n);
void pop();
void display();
};
void ListStack::push(node n)
{
node *newNode;
newNode= new node;
// cout<<"Enter number to add on stack";
// cin>>newNode->num;
newNode->num;
newNode->next=top;
top=newNode;
}
void ListStack::display()
{
node *n;
n= new node;
n=top;
while(n!=NULL){
cout << n->num<<" ";
n= n-> next;
}
}
int main(){
ListStack l;
int a;
cout<<"Enter a digit with base 10 : ";
cin>>a;
cout<<"\nbinary of entered num is : \n";
node *r;
r= new node;
while(a!=0){
a%2=r->num;
push(r);
cout<<r->num;
a/=2;
}
}
So I'm trying to solve this problem :
Given an array arr[] of integers and an integer sum, the task is to
count all subsets of the given array with a sum equal to a given sum.
Note: Answer can be very large, so, output answer modulo 10^9+7
Now this is the solution I'm trying out here:
class Solution{
private:
vector<vector<int>> t;
public:
Solution() {
t.resize(1001, vector<int> (1001,-1));
}
int perfectSum(int arr[], int n, int sum)
{
long long int result = fmod(sumrecursive(arr, n, sum),(pow(10,9)+7));
return result;
}
long long int sumrecursive(int arr[], int n, int sum){
if(sum==0){
return 1;
}
if(n==0){
return 0;
}
if(t[n][sum] != -1){
return t[n][sum];
}
if(arr[n-1]>sum){
return t[n][sum] = sumrecursive(arr, n-1, sum);
} else {
return t[n][sum] = sumrecursive(arr,n-1, sum-arr[n-1]) + sumrecursive(arr, n-1, sum);
}
}
};
Now this code is not working after some certain input:
I don't know on how to proceed in solving this problem at this point. Ideally according to the code I have written the input is within the grasp of the code and output should've been correct but unfortunately it is not the case. I wanted to ask if someone could spot on where the problem might be in the code or guide me on how to debug where the problem is in the code.
You are probably encountering integer overflow along the way.
You are taking the mod only right before ending the function, but your cache is of type int, so when placing too big numbers - you are losing some data due to overflow.
For example, if the input array is
832461905
The output is
1357902468
I think this can be done in two steps
1) sort data
012345678
2) move odd numbers in front of even numbers by preserving order
To do so, we can have two pointers
Initially one points to the beginning and the other points to the end
Move the head util even numbers are found
The move the tail until odd numbers are found
Swap data at the pointers
Do the above until the two pointers meet
My question is if we can solve the problem by using one step rather than two
All you need is a little comp-function for sorting:
bool comp(int x, int y)
{
if (x % 2 == y % 2) return x < y;
return x % 2 > y % 2;
}
...
sort(your_array.begin(), your_array.end(), comp);
Yes, it can be done in one step.
Write your own comparison function, and use std::sort in C++:
sort(data.begin(),data.end(),comp);
bool comp(int x,int y)
{
if (x%2==0)
{
if(y%2==0)
{
return x<y; // if both are even
}
else
{
return false; // if only x is even
}
}
else
{
if(y%2==0)
{
return true;
}
else
{
return x<y;
}
}
}
Under the <algorithm> library in C++ you can use sort to order the numbers and then stable_partition to separate by odd and even.
Like so:
auto arr = std::valarray<int>{8,3,2,4,6,1,9,0,5};
std::sort(std::begin(arr), std::end(arr));
std::stable_partition(std::begin(arr), std::end(arr), [](int a){ return a % 2; });
Resulting in a rather succinct solution.
I am considering you are familiar with C++. See my code snippet, and yes it can be done in a step:
#include <iostream>
#include <stdio.h>
#include <algorithm>
bool function(int a, int b) {
if(a%2 != b%2) { /* When one is even and another is odd */
if(a&1) {
return true;
} else {
return false;
}
} else { /* When both are either odd or even */
return (a<b);
}
}
int main() {
int input[10005]; /* Input array */
int n = -1, i;
/* Take the input */
while(scanf("%i", &input[++n]) != EOF);
/* Sort according to desire condition */
std::sort(input, input+n, function);
/* Time to print out the values */
for(i=0; i<n; i++) {
std::cout << input[i] << " ";
}
return 0;
}
Any confusion, comments most welcome.
I was asked this question in one of my recent interviews. A three digit lock can have its key value between range "000" - "999". So basically 1000 combinations have to be tried to open the lock. So I had to generate the shortest string such that all possible combinations (i.e between "000"-"999") would be checked. So for example if we had string "01234" then it would check the combinations "012", "123" and "234". So I had to generate a string which would check all combination. I tried to use a hashset to implement this, where I started with "000" and then took the last two character in string i.e "00" and then appended a new number from 0 to 9 and checked if it existed in hashset. If not I appended that number to output string and repeated the process. Is there any other efficient and clean way to solve this problem.
The procedure you described is based on the assumption that the shortest string has every code exactly once. It turns out that this assumption is correct.
Here's a simple backtracking implementation (C++):
#include <stdio.h>
bool used[1000];
int digits[33333];
bool backtrack(int index, int total)
{
if (total == 1000)
{
printf("%d\n", index);
for (int i = 0; i < index; ++i) {
printf("%d", digits[i]);
}
printf("\n");
return true;
}
for (int d = 0; d < 10; ++d)
{
int prev = 100*digits[index-2]+10*digits[index-1]+d;
if (!used[prev]) {
digits[index] = d;
used[prev] = true;
if (backtrack(index+1, total+1))
return true;
used[prev] = false;
}
}
}
int main(void) {
digits[0] = 0;
backtrack(2, 0);
return 0;
}
Output:
1002
00010020030040050060070080090110120130140150160170\
18019021022023024025026027028029031032033034035036\
03703803904104204304404504604704804905105205305405\
50560570580590610620630640650660670680690710720730\
74075076077078079081082083084085086087088089091092\
09309409509609709809911121131141151161171181191221\
23124125126127128129132133134135136137138139142143\
14414514614714814915215315415515615715815916216316\
41651661671681691721731741751761771781791821831841\
85186187188189192193194195196197198199222322422522\
62272282292332342352362372382392432442452462472482\
49253254255256257258259263264265266267268269273274\
27527627727827928328428528628728828929329429529629\
72982993334335336337338339344345346347348349354355\
35635735835936436536636736836937437537637737837938\
43853863873883893943953963973983994445446447448449\
45545645745845946546646746846947547647747847948548\
64874884894954964974984995556557558559566567568569\
57657757857958658758858959659759859966676686696776\
78679687688689697698699777877978878979879988898999\
00
The procedure is efficient.
How to sort list of values using only one variable?
A solution in C:
#include <stdio.h>
int main()
{
int list[]={4,7,2,4,1,10,3};
int n; // the one int variable
startsort:
for (n=0; n< sizeof(list)/sizeof(int)-1; ++n)
if (list[n] > list[n+1]) {
list[n] ^= list[n+1];
list[n+1] ^= list[n];
list[n] ^= list[n+1];
goto startsort;
}
for (n=0; n< sizeof(list)/sizeof(int); ++n)
printf("%d\n",list[n]);
return 0;
}
Output is of course the same as for the Icon program.
I suspect I'm doing your homework for you, but hey it's an interesting challenge. Here's a solution in Icon:
procedure mysort(thelist)
local n # the one integer variable
every n := (1 to *thelist & 1 to *thelist-1) do
if thelist[n] > thelist[n+1] then thelist[n] :=: thelist[n+1]
return thelist
end
procedure main(args)
every write(!mysort([4,7,2,4,1,10,3]))
end
The output:
1
2
3
4
4
7
10
You could generate/write a lot of sorting-networks for each possible list size. Inside the sorting network you use a single variable for the swap operation.
I wouldn't recommend that you do this in software, but it is possible nevertheless.
Here's a sorting-routine for all n up to 4 in C
// define a compare and swap macro
#define order(a,b) if ((a)<(b)) { temp=(a); (a) = (b); (b) = temp; }
static void sort2 (int *data)
// sort-network for two numbers
{
int temp;
order (data[0], data[1]);
}
static void sort3 (int *data)
// sort-network for three numbers
{
int temp;
order (data[0], data[1]);
order (data[0], data[2]);
order (data[1], data[2]);
}
static void sort4 (int *data)
// sort-network for four numbers
{
int temp;
order (data[0], data[2]);
order (data[1], data[3]);
order (data[0], data[1]);
order (data[2], data[3]);
order (data[1], data[2]);
}
void sort (int *data, int n)
{
switch (n)
{
case 0:
case 1:
break;
case 2:
sort2 (data);
break;
case 3:
sort3 (data);
break;
case 4:
sort4 (data);
break;
default:
// Sorts for n>4 are left as an exercise for the reader
abort();
}
}
Obviously you need a sorting-network code for each possible N.
More info here:
http://en.wikipedia.org/wiki/Sorting_network
In java:
import java.util.Arrays;
/**
* Does a bubble sort without allocating extra memory
*
*/
public class Sort {
// Implements bubble sort very inefficiently for CPU but with minimal variable declarations
public static void sort(int[] array) {
int index=0;
while(true) {
next:
{
// Scan for correct sorting. Wasteful, but avoids using a boolean parameter
for (index=0;index<array.length-1;index++) {
if (array[index]>array[index+1]) break next;
}
// Array is now correctly sorted
return;
}
// Now swap. We don't need to rescan from the start
for (;index<array.length-1;index++) {
if (array[index]>array[index+1]) {
// use xor trick to avoid using an extra integer
array[index]^=array[index+1];
array[index+1]^=array[index];
array[index]^=array[index+1];
}
}
}
}
public static void main(final String argv[]) {
int[] array=new int[] {4,7,2,4,1,10,3};
sort(array);
System.out.println(Arrays.toString(array));
}
}
Actually, by using the trick proposed by Nils, you can eliminate even the one remaining int allocation - though of course that would add to the stack instead...
In ruby:
[1, 5, 3, 7, 4, 2].sort
You dont, it is already sorted. (as the question is vague, I shall assume variable is a synonym for an object)
If you have a list (1 5 3 7 4 2) and a variable v, you can exchange two values of the list, for example the 3 and the 7, by first assigning 3 to v, then assigning 7 to the place of 3, finally assigning the value of v to the original place of 7. After that, you can reuse v for the next exchange. In order to sort, you just need an algorithm that tells which values to exchange. You can look for a suitable algorithm for example at http://en.wikipedia.org/wiki/Sorting_algorithm .