I'm writing a piece of code for a slot machine project, I have two arrays working.
I would like to compare one element of array 1 with multiple element of array 2.
This is my current piece of code, I took a swing at it but I don't think this is correct.
char arrayOne[10]{ 1, 1, 2, 2, 3, 4, 4, 5, 5 };
char arrayTwo[10]{ 1, 2, 3, 4, 5 };
if (arrayTwo[0] == arrayOne[0 - 1])
cout << "The Numbers are the same";
else
cout << "the numbers are different";
_getch();
In C++, the syntax you've written is the same as: arrayTwo[0] == arrayOne[-1], which I'm fairly sure we both agree is not what you want.
You're looking for:
((arrayTwo[0] == arrayOne[0]) and (arrayTwo[0] == arrayOne[1]))
If you want to match against an arbitrary number of elements, then you should learn about loops:
bool truthiness = true;
for (int i=0; i<10; ++i) {
truthiness = truthiness and (arrayTwo[0] == arrayOne[i]);
}
if (truthiness) {
cout << "The numbers are the same";
} else {
cout << "The numbers are different";
}
You should use a loop. I've written this small function for you...
int
array_range_compare (char *array, int compare_value, int start, int end)
{
for (int i = start; i <= end; i++) {
if (compare_value != array[i]) {
return 0;
}
}
return 1;
}
This will compare the value of compare_value to the values of keys start through end in array. For you array is arrayOne, start is 0, end is 1, and compare_value is arrayTwo[0], all of the variables but array are integers.
You can use this function like so...
char arrayOne[10] = { 1, 1, 2, 2, 3, 4, 4, 5, 5 };
char arrayTwo[10] = { 1, 2, 3, 4, 5 };
if (array_range_compare (arrayOne, arrayTwo[0], 0, 1)) {
std::cout << "The Numbers are the same";
} else {
std::cout << "the numbers are different";
}
Related
I have this exercise:
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, input [3, 4, -1, 1] should give 2 and input [1, 2, 0] should give 3.
You can modify the input array in-place.
My implementation:
template <typename In_It>
int missingPositiveInt(In_It first, In_It last){
first = std::find_if( first, last, [](int x){return x > 0;} );
if(first == last || *first > 1)
return 1;
for( auto next = first; (++next != last) && ( !(*next - *first > 1) ); )
++first;
return *first + 1;
}
int main(){
std::vector<int> v{5, 2, -1, 7, 0};
std::sort(v.begin(), v.end());
std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n';
v = {2, -1, 1, 0};
std::sort(v.begin(), v.end());
std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n';
v = {5, 2, -1, 7, 0};
std::sort(v.begin(), v.end());
std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n';
v = {3, 4, -1, 1};
std::sort(v.begin(), v.end());
std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n';
v = {1, 2, 0};
std::sort(v.begin(), v.end());
std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n';
std::cout << '\n';
}
The output:
1
3
1
2
3
The program works just fine but I use the algorithm std::find_if to find the first positive value in the sequence (sorted sequence) and that algorithm does a linear search.
As long as the input sequence is already sorted I want to use some binary search algorithm to speed the process.
I tried using std::binary_search but it requires an argument to be searched for. What I need is to get a version that takes a unary predicate and applies a binary search or any other faster algorithm to find the lowest positive value in the sequence so I can write:
auto it = binary_search(first, last, [](int x){ return x > 0; });
Is it possible? Is my code fine or I need to modify it. So any suggestion, hint is highly appreciated.
Yes, std::partition_point does exactly what you want.
Partial solution based on #numzero's answer. This doesn't handle negative numbers or zero in the array but you can handle that by linearly preprocessing the array to remove them beforehand. It just marks each index as "found" by negating it, then later looks for the first non negative value and thats the one. Even though its a partial solution it shows the core algorithm.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 4, 6, 7, 2, 7, 7, 8, 3};
int arrSize = sizeof(arr)/sizeof(int);
for(int i=0; i<arrSize; ++i)
{
int val = abs(arr[i]);
if(val > 0 && val-1 < arrSize)
{
if (arr[val-1]>0)
{
arr[val-1] = -arr[val-1];
}
}
}
for(int i=0; i<arrSize; ++i)
{
if(arr[i] > 0)
{
std::cout << "Smallest is " << (i+1) << std::endl;
return 0;
}
}
std::cout << "Nothing found!" << std::endl;
// your code goes here
return 0;
}
For each integer in an array of positive integers, find the index of the closest integer that is greater than the current integer. Also, we need to search for the answer only to the left of the current integer.
For example -
Input array - [ 5, 4, 3, 6, 2, 3]
Output array - [ -1, 0, 1, -1, 3, 3]
Assign -1 to those numbers which don't have an answer.
There is a simple O(n^2) method, for each number run a for loop from the previous number to the beginning of the array.
for(int i=0; i<n; ++i)
{
output[i] = -1;
for(int j=i-1; j>=0; --j)
{
if(input[j] > input[i])
{
output[i] = j;
break;
}
}
}
This method is inefficient when 'n' is large. Is there a more efficient way?
I believe one popular O(n) solution is to use a stack, maintaining a descending sequence (hopefully the algorithm is clear enough from the commented code):
function f(A){
let stack = []
let output = []
for (let i=0; i<A.length; i++){
// While there are lower or
// equal elements on top of
// the stack
while (stack.length && A[ stack[stack.length-1] ] <= A[i])
stack.pop();
// The next greater element
// to the left
if (stack.length)
output.push(stack[stack.length-1]);
// There was none
else
output.push(-1);
stack.push(i);
}
return output;
}
var As = [
[5, 4, 3, 6, 2, 3],
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[0, 3, -1, 5, 4]
];
for (let A of As){
console.log(`${ A }`);
console.log(`${ f(A) }`);
console.log('');
}
The proposed answer is an adaption of : https://www.geeksforgeeks.org/find-the-nearest-smaller-numbers-on-left-side-in-an-array/
The main idea is to use a stack to remember processed value. In the link, they care about the value but it can easily be adapted to output indices.
#include <iostream>
#include <vector>
#include <stack>
std::vector<int> function(std::vector<int> input) {
std::vector<int> output;
output.reserve(input.size());
// Create an empty stack
// first element of the pair is the index. second is the value
std::stack<std::pair<int,int>> S;
// Traverse all array elements
for (int i=0; i<input.size(); i++)
{
// Keep removing top element from S while the top
// element is less than or equal to arr[i]
while (!S.empty() && S.top().second <= input[i])
S.pop();
// If all elements in S were greater than arr[i]
if (S.empty())
output.push_back(-1);
else //Else print the nearest smaller element
output.push_back(S.top().first);
// Push this element
S.push({i, input[i]});
}
return output;
}
int main() {
std::vector<int> input{5, 4, 3, 6, 2, 3};
std::vector<int> output = function(input);
for(int index : output) {
std::cout << index << ' ';
}
return 0;
}
Output:
-1 0 1 -1 3 3
Compiler explorer : https://godbolt.org/z/8W3ecv
I'm having a trouble for a long time in a problem related to array and loops.
Assume an array like:
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
The program should print the expected column as shown (note that the table is an idea for clarification of what I actually want to achieve):
max: expected arr[index] for max
------------------------------------
2 : 3 5 value of: arr[0]
3 : 6, 8, 10 value of: arr[3]
1 : 9 value of: arr[7]
This is what I've tried so far:
#include <iostream>
int main(void) {
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
int max = arr[0];
int i = 1, it = i;
for (; i <= max; i++) {
if (i == max) {
std::cout << arr[i] << std::endl;
max = arr[it + 1]; // when loop end has come, increment max to next element value
it = i + 2; // incrementing iterator by 2 next element position (after max)
} else {
std::cout << arr[i] << ' '; // when loop is executing
}
}
return 0;
}
What it actually prints which is unexpected V/S what it should print:
3 5 | 3, 5
3 6 8 | 6, 8, 10
10 1 9 | 1, 9
10 | <nothing>
The program is about to get max value and print the next elements until max value reaches the number of element position.
Where the problem's occurring and how to fix it? Please let me know.
So I rewrote your code, frankly I couldn't follow it, it seems a bit confused with variable names that seem a bit off.
Here's some working code. The two key concepts in the code are the place where each block starts (the variable start) and the size of each block (the variable count). Plus I use the size of the whole array sizeof(arr)/sizeof(arr[0]) to terminate the outer loop. Something that wasn't present in your code. If you are using C++17, you can use std::size(arr) instead of sizeof.
int main(void) {
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
size_t start = 0;
while (start < sizeof(arr)/sizeof(arr[0]))
{
int count = arr[start];
for (int i = 0; i < count; ++i)
{
std::cout << arr[start + i + 1] << ' ';
}
std::cout << std::endl;
start += count + 1;
}
}
The output is
3 5
6 8 10
9
Ask the user for a number between 1 and 9. If the user does not enter a number between 1 and 9, repeatedly ask for an integer value until they do. Once they have entered a number between 1 and 9, print the array.Given the array- int array[] = { 4, 6, 7, 3, 8, 2, 1, 9, 5 };
#include<iostream>
int printArray(){
int arraySize,i;
int array[] = { 4, 6, 7, 3, 8, 2, 1, 9, 5 };
arraySize=sizeof(array)/sizeof(array[0]);
std::cout<<"The length of the array is:"<<" "<<arraySize<<"\n";
for(i=0;i<arraySize;i++){
std::cout<<array[i]<<"\n";
}
}
int main(){
tryAgain:
int x;
std::cout<< "Enter any number between 1 and 9"<<"\n";
std::cin>>x;
if(x<=9 && x>=1){
printArray();
}
else
goto tryAgain;
return 0;
}
What you have here is undefined behaviour caused by not returning a valid value from function printArray that is supposed to return an int.
The standard addresses this issue:
9.6.3 The return statement
...
2. ... Otherwise, flowing off the end of a function other than main results in undefined behavior.
Compiling with -Wall option in GCC produces this warning:
warning: no return statement in function returning non-void [-Wreturn-type]
Since the function only prints data, you should have void instead of int as return type.
I think you shouldn't use goto, use for
The line int printArray(){ should be void printArray(){ for you needn't return
The follow code could work:
#include <iostream>
void printArray(){
int arraySize, i;
int array[] = { 4, 6, 7, 3, 8, 2, 1, 9, 5 };
arraySize = sizeof(array) / sizeof(array[0]);
std::cout << "The length of the array is:" << " " << arraySize << "\n";
for (i = 0; i < arraySize; ++i)
std::cout<<array[i]<<"\n";
}
int main(){
for (;;) {
std::cout << "Enter any number between 1 and 9"<<"\n";
int x;
std::cin >> x;
if(std::cin.fail()) {
std::cin.clear();
std::cin.ignore(1024, '\n');
continue;
}
if (x < 1 || x > 9)
continue;
printArray();
break;
}
return 0;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So, I'm creating a program to create a (sort of) simulation of a melee deathmatch video game (not actually making a video game at the moment, just making simple AIs with goals to kill each other). In order to do this, I am using a tile-based, turn-based system.
Now the introduction is out of the way, here is the specific problem: in one of the arrays I am using, the last value is stored incorrectly in RAM, no matter how many variables in the array. Here is the relevant code:
(I will post all the code I have at the bottom of this, but the problem is in here)
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
int npcTileAttacker[] = { 0, 0, 0, 0, 0};
int s = 0;
while (s < 6)
{
cout << "The value that is being selected from the array is " << s << endl;
cout << npcTileAttacker[s] << endl;
s++;
cout << "The value of s has now been set to " << s << endl;
}
This outputs:
The value that is being selected from the array is 0
0
The value of s has now been set to 1
The value that is being selected from the array is 1
0
The value of s has now been set to 2
The value that is being selected from the array is 2
0
The value of s has now been set to 3
The value that is being selected from the array is 3
0
The value of s has now been set to 4
The value that is being selected from the array is 4
0
The value of s has now been set to 5
The value that is being selected from the array is 5
-858993640
The value of s has now been set to 6
Obviously, this last value from the array is incorrect. What I want to know is why this would be happening.
In addition to this, when the program ends, I get an error message:
"Run-Time Check Failure #2 - Stack around the variable 'npcTileAttacker' was corrupted."
I have tried placing the output values of s and the array piece of code around other arrays in the program, resulting in the same problem occuring.
Here is my full code, if required:
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
int numberOfNPCs = 5;
//Remember whose alive (so we can skip the dead's turns)
int npcAlive[5] = { 1, 1, 1, 1, 1 };
/*This determines what action is going to be carried out on this square. For the moment:
if npcTileActivity[n] = 1;
the goals is death
WARNING! THIS WILL RESULT IN BUGS!!! I need to figure out a way that allows multiple activities on a tile
(maybe apply actions onto NPCs directly, rather than onto their tiles)
*/
int npcTileActivity[] = { 0, 0, 0, 0, 0};
//This tells you who is doing the action on this tile
int npcTileAttacker[5] = { 1, 2, 3, 4, 0 };
int s = 0;
while (s < 6)
{
cout << "The value that is being selected from the array is " << s << endl;
cout << npcTileAttacker[s] << endl;
s++;
cout << "The value of s has now been set to " << s << endl;
}
//This determines whether or not the NPC will fight back. Currently pointless, as this will just kill them.
int npcPacifism[5] = { 0 };
//This is their HP
int npcDefense[5] = {5, 5, 5, 5, 5};
//This is the default damage (presumably this is done with knives)
int npcOffense[5] = {1, 1, 1, 1, 1};
/*This determines what each NPC wants to do.
1 - Kill Target
*/
int npcGoal[5] = {1, 1, 1, 1, 1};
//This is the NPC they are aiming at
int npcTarget[5] = {1, 2, 3, 4, 0};
/*The x coord for their target. In the future:
-I want this to be able to be changed during the sim
-This should be disabled until the NPC can find out where their target is
*/
int npcGoalLocationX[5] = {4, 1, 4, 3, 1};
/* The Y coord for their target
*/
int npcGoalLocationY[5] = {2, 3, 4, 2, 1};
/*Their x coord.
This will change, then the all npcGoalLocations need to be updated
*/
int npcLocationX[5] = {1, 4, 1, 4, 3};
/* Their y coord.
*/
int npcLocationY[5] = {1, 2, 3, 4, 2};
int m = 1;
while (m != 0)
{
int i = 0;
//Loop until every npc has had a turn
while (i < (numberOfNPCs + 1))
{
/*npcGoalLocationY[i] = npcLocationY[npcTarget[i]];
npcGoalLocationY[i] = npcLocationY[npcTarget[i]];*/
if (npcAlive[i] = 1)
{
/* Tile activities:
1 - Kill occupant
*/
if (npcTileActivity[i] = 1)
{
cout << "This shouldn't be the first thing." << endl;
//This gets the attack and defense values for the appropriate acting NPC
int j = 0;
while (j < (numberOfNPCs + 1))
{
if (npcTileAttacker[i] = j)
{
//Defender's HP - Attacker's damage
int rollAttack1 = npcDefense[i] - npcOffense[j];
if (rollAttack1 > 0)
{
npcDefense[i] = rollAttack1;
cout << "NPC " << j << " attacks NPC " << i << endl;
if (npcPacifism[i] = 0)
{
//Defender retaliates
int rollAttack2 = npcDefense[j] - npcOffense[i];
if (rollAttack2 > 0)
{
npcDefense[j] = rollAttack2;
cout << "NPC " << i << " retaliates" << endl;
}else
{
npcAlive[j] = 0;
cout << "NPC " << j << " dies" << endl;
}
}
}else
{
npcAlive[i] = 0;
cout << "NPC " << i << " dies" << endl;
}
}
j++;
}
}else
{
cout << "This should be the first." << endl;
if (npcGoal[i] != 0)
{
if (npcGoalLocationX[i] = npcLocationX[i])
{
if (npcGoalLocationY[i] = npcLocationY[i])
{
//The Tile Activity of the current NPC's target is set to whatever the current NPC's goal is
npcTileActivity[npcTarget[i]] = npcGoal[i];
}
}
if (npcGoalLocationX[i] > npcLocationX[i])
{
npcLocationX[i]++;
}
if (npcGoalLocationX[i] < npcLocationX[i])
{
npcLocationX[i]--;
}
if (npcGoalLocationY[i] > npcLocationY[i])
{
npcLocationY[i]++;
}
if (npcGoalLocationY[i] < npcLocationY[i])
{
npcLocationY[i]--;
}
}
}
}
i++;
}
cin >> m;
}
return 0;
}
Also, I get a problem (around the lines which cout "This should be first" and "This shouldn't be the first thing"): The one which shouldn't be first is first and the one which should be first never even executes. This is probably related to the array error, however.
Thanks for your assistance.
Your condition is off by one:
while (s < 6)
should be
while (s < 5)
The array { 0, 0, 0, 0, 0} has five elements, so valid indexes are 0,1,2,3,4.
Your condition stops when s < 6 is false, so it's still true for s == 5.
Your array has only 5 cells:
int npcTileAttacker[] = { 0, 0, 0, 0, 0};
That is, s should go from 0 to 4, instead of 0 to 5.
The "random" value that you are seeing is in fact whatever value was there on the stack after npcTileAttacker array since you are overflowing that array.
The size of your array is 5. Hence the valid indices are from 0-4. So, npcTileAttacker[5] will always post garbage.
You're out by 1 in your while loop expression.
You'd also be better off using a for loop and not hard coding the length of the array. Try something like this:
int npcTileAttacker[] = { 0, 0, 0, 0, 0};
int npcTileAttackerLength = sizeof(npcTileAttacker)/sizeof(npcTileAttacker[0]);
for(int s=0; s<npcTileAttackerLength; s++)
{
cout << "The value that is being selected from the array is " << s << endl;
cout << npcTileAttacker[s] << endl;
}
This way the length variable will always hold the number of items in the array.