I need to get the length of filled rows ( filled rows means a rows which contains at least one 1 ) of 2D int array in c#.
For ex..
1 1 1 0 1
0 1 1 1 1
1 1 1 1 1
0 0 0 0 0
Now the filled rows length=3 and col=4.
That is what i need...
I am expecting that you are storing these values in two dimensional integer array e.g.
int[][] a = {new int[] {1, 1, 0, 1}, new int[] {0, 1, 1, 1}, new int[] {1, 1, 1, 1}, new int[] {0, 0, 0, 0}};
Following is the LINQ for counting rows which has atleast one 1.
int filledRowsCount = a.Count(i => i.Any(ii => ii == 1));
int[][] intarray = { new int[] { 1, 2, 3 },
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3 } };
**int c = intarray.Count();**//for rows Length = 4
int b = intarray[0].Count();//for columns length =3
you can use also:
int d = intarray.GetLength(0);//for rows length = 4
Related
I have a program where I use a vector to simulate all the possible outcomes when counting cards in blackjack. There's only three possible values, -1, 0, and 1. There's 52 cards in a deck therefore the vector will have 52 elements, each assigned one of values mentioned above. The program works when I scale down the size of the vector, it still works when I have it as this size however I get no output and get the warning "warning C4267: '=': conversion from 'size_t' to 'int', possible loss of data".
#include<iostream>
#include"subtracter.h"
#include<time.h>
#include<vector>
#include<random>
using namespace std;
int acecard = 4;
int twocard = 4;
int threecard = 4;
int fourcard = 4;
int fivecard = 4;
int sixcard = 4;
int sevencard = 4;
int eightcard = 4;
int ninecard = 4;
int tencard = 16;
// declares how many of each card there is
vector<int> cardvalues = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
// a vector that describes how many cards there are with a certain value
vector<int> deck = { acecard, twocard, threecard, fourcard, fivecard, sixcard, sevencard, eightcard, ninecard, tencard };
// a vector keeping track of how many of each cards there's left in the deck
int start()
{
int deckcount;
deckcount = 0;
int decksize;
decksize = cardvalues.size();
while (decksize >= 49)
{
deckcount += cardsubtracter(cardvalues);
};
return deckcount;
}
int cardcounting()
{
int deckcount;
deckcount = start();
deckcount += cardsubtracter(cardvalues);
return deckcount;
}
int main()
{
int value;
value = cardcounting();
int size;
size = cardvalues.size();
cout << value << "\n";
cout << size;
return 0;
}
#include<iostream>
#include<random>
using namespace std;
int numbergenerator(int x, int y)
{
int number;
random_device generator;
uniform_int_distribution<>distrib(x, y);
number = distrib(generator); //picks random element from vector
return number;
}
int cardsubtracter(vector<int> mynum)
{
int counter;
int size;
int number;
size = mynum.size() - 1;//gives the range of values to picked from the vectorlist
number = numbergenerator(0, size);//gives a random number to pick from the vectorlist
counter = mynum[number]; // uses the random number to pick a value from the vectorlist
mynum.erase(mynum.begin()+number); //removes that value from the vectorlist
return counter;
}
I looked up the max limit of vectors and it said that vectors can hold up 232 values with integers, which should work for this. So I also tried creating a new file and copying the code over to that in case there was something wrong with this file.
There could be different reasons why a vector may not be able to hold all 52 elements. Some possible reasons are:
Insufficient memory: Each element in a vector requires a certain amount of memory, and the total memory required for all 52 elements may exceed the available memory. This can happen if the elements are large, or if there are many other variables or data structures in the environment that consume memory.
Data type limitations: The data type of the vector may not be able to accommodate all 52 elements. For example, if the vector is of type "integer", it can only hold integers up to a certain limit, beyond which it will overflow or produce incorrect results.
Code errors: There may be errors in the code that prevent all 52 elements from being added to the vector. For example, if the vector is being filled in a loop, there may be a mistake in the loop condition or in the indexing that causes the loop to terminate early or skip some elements.
To determine the exact reason for the vector not being able to hold all 52 elements, it is necessary to examine the code, the data types involved, and the memory usage.
char arrA[ 6 ] = { 1, 2, 3, 4, 5, 0 };
char arrB[ 6 ] = {};
void setup(){
strcpy( arrB, arrA );
}
Hi all, I obtained the code above from here. My case is I need to use int arrA[6] instead of char arrA[6] when initializing variables so that it remains as values and not string. May I ask how do I actually accomplish it with arduino code. The link above only uses string as array and not numbers. Thank you for reading and have a nice day !!!
You can write a for loop to copy the contents of arrA to arrB.
int arrA[ 6 ] = { 1, 2, 3, 4, 5, 0 };
int arrB[ 6 ];
void setup(){
for(int i = 0; i < (sizeof(arrA)/sizeof(arrA[0])); i++)
{
arrB[i] = arrA[i];
}
}
Traditional Longest Increasing Subsequence problem.
This is recursion version ( not DP version )
I realized that version1 code had a bug, so I changed it to version2.
I don't clearly understand why version2 works and version1 has a bug for input A0
Please see version 1 and version2 below:
static int lis1(int[] v) {
int maxLen = 1;
for(int i = 1; i < v.length; i++) {
List<Integer> w = new ArrayList<Integer>();
for( int j = 0; j < i; j++) {
if( v[j] < v[i] ) {
w.add(v[j]);
}
}
// it used to be the following one line which has bug for input A0
//cand = lis1(l2a(w)) + 1; // version1
// so I changed it to the following, but can't clearly understand why it works.
// without this part, it has but for input A0
int cand = 1; // version2
if(v[i-1] < v[i])
cand = lis1(l2a(w)) + 1;
else
cand = lis1(l2a(w));
maxLen = Math.max(maxLen, cand);
}
return maxLen;
}
public static void main(String[] args) {
int[] A0 = {3, 2, 5, 6}; // for this input version1 had a bug which printed out 4 ( instead of 3 )
int[] A1 = {1, 2, 3, 3, 2, 4, 6, 7}; // 6
int[] A2 = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; // 6
int[] A3 = { 5, 0, 4, 2, 3, 7, 1 }; // 4
int[] A4 = { 2, 7, 3, 4, 9, 8, 12 }; // 5
int[] A5 = {3, 4, 2, 5 }; // 3
Actually... neither of your version works. Try putting A0={3,2,7,6}, your v2 returns 2, obviously wrong.
As for v1, for v={3,2} the answer should be 1, right? Let's see what your code does. When index i=1, your w after inner for loop equals {}. Then you made a recursive call to w={}, which should've returned 0, but it returns 1. Why, because of your maxlen variable, which is wrongly initialized with 1. This error propagates to entire {3,2,5,6} and gives wrong answer.
v2 accidentally solves this problem because your if condition then fails (3<2), and it returns the previously returned 1.
Just delete entire version 2, correct maxlen initialization. And start outer loop for(int i = 1; i < v.length; i++) with i=0, else you will get 0 for single-element array.
static int lis1(int[] v) {
int maxLen = 0;
for(int i = 0; i < v.length; i++) {
List<Integer> w = new ArrayList<Integer>();
for( int j = 0; j < i; j++) {
if( v[j] < v[i] ) {
w.add(v[j]);
}
}
cand = lis1(l2a(w)) + 1; // version1
maxLen = Math.max(maxLen, cand);
}
return maxLen;
}
Sorry if I'm not specific, but I have my code in working order, but I do not know how to separate the two different array outputs(?). Here's my code:
package code;
public class ArrayPrinter{
public static void main(String[] args) {
int FirstArray[][] = { {5, 6, 7, 8,} , {2, 4, 6, 8} , {8, 7, 9, 1} , {3, 5, 1, 2} };
printarray(FirstArray);
}
public static void printarray(int a[][]) {
for( int row = 0 ; row < a.length ; row++ ) {
for ( int column = 0 ; column < a[row].length ; column++ ) {
System.out.print( a[row][column] + " ");
}
System.out.println();
}
int SecondArray[][] = { {1, 2} , {3, 4, 5} , {6} , {7, 8, 9} };
printarray1(SecondArray);
}
public static void printarray1(int b[][]) {
for( int row = 0 ; row < b.length ; row++ ) {
for ( int column = 0 ; column < b[row].length ; column++ ) {
System.out.print( b[row][column] + " ");
}
System.out.println();
}
}
}
Here is the output:
5 6 7 8
2 4 6 8
8 7 9 1
3 5 1 2
1 2
3 4 5
6
7 8 9
Here is what I want it to look like
5 6 7 8
2 4 6 8
8 7 9 1
3 5 1 2
(well it wont let me add spaces, but I want these two sperated)
1 2
3 4 5
6
7 8 9
Help please.
Put an extra System.out.println() after the outermost for loop like...
public static void printarray(int a[][]) {
for( int row = 0 ; row < a.length ; row++ ) {
for ( int column = 0 ; column < a[row].length ; column++ ){
System.out.print( a[row][column] + " ");
}
System.out.println();
}
System.out.println();
int SecondArray[][] = { {1, 2} , {3, 4, 5} , {6} , {7, 8, 9} };
printarray1(SecondArray);
}
Also your two print functions look identical and could be combined.
Is there a simple way to recover an index in nested for loops? For example, in for loops which construct Pascals triangle
int index = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N-i; ++j)
index++;
is there a way to recover i and j given only index?
I am adding this as a second answer since it is in a different language (now C) and has a more direct approach. I am keeping the original answer since the following code is almost inexplicable without it. I combined my two functions into a single one to cut down on function call overhead. Also, to be 100% sure that it answers the original question, I used the loops from that question verbatim. In the driver function I show explicitly that the output is correct for N = 4 and then stress-test it for N = 10000 (with a total of 100,000,000 passes through the inner loop). I don't have any formal timing code, but it takes about 1 second on my machine to run through and test those 100 million cases. My code assumes a 32-bit int. Change to long if needed:
#include <stdio.h>
#include <math.h>
void from_index(int n, int index, int *i, int *j);
int main(void){
int N;
int ri,rj; //recovered i,j
N = 4;
int index = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N-i; ++j){
from_index(N,index,&ri,&rj);
printf("i = %d, j = %d, index = %d, ",i,j,index);
printf("recovered i = %d, recovered j = %d\n",ri,rj);
index++;
}
//stress test:
N = 10000;
index = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N-i; ++j){
from_index(N,index,&ri,&rj);
if(i != ri || j != rj){
printf("Don't post buggy code to Stack Overflow!\n");
printf("(i,j) = (%d,%d) but recovered indices are (%d,%d)\n",i,j,ri,rj);
return 0;
}
index++;
}
printf("\nAll %d tests passed!\n",N*N);
return 0;
}
void from_index(int n, int index, int *i, int *j){
double d;
d = 4*n*(n+1) - 7 - 8 * index;
*i = floor((-1 + sqrt(d))/2);
*j = *i * (*i + 1)/2;
*j = n*(n+1)/2 - 1 - index - *j;
*j = *i - *j;
*i = n - *i - 1;
}
Output:
i = 0, j = 0, index = 0, recovered i = 0, recovered j = 0
i = 0, j = 1, index = 1, recovered i = 0, recovered j = 1
i = 0, j = 2, index = 2, recovered i = 0, recovered j = 2
i = 0, j = 3, index = 3, recovered i = 0, recovered j = 3
i = 1, j = 0, index = 4, recovered i = 1, recovered j = 0
i = 1, j = 1, index = 5, recovered i = 1, recovered j = 1
i = 1, j = 2, index = 6, recovered i = 1, recovered j = 2
i = 2, j = 0, index = 7, recovered i = 2, recovered j = 0
i = 2, j = 1, index = 8, recovered i = 2, recovered j = 1
i = 3, j = 0, index = 9, recovered i = 3, recovered j = 0
All 100000000 tests passed!
In this particular case we have
index = N+(N-1)+...+(N-i+1) + (j+1) = i(2N-i+1)/2 + (j+1) = -i^i/2 + (2N-1)i/2 + (j+1)
with j in the interval [1,N-i].
We neglect j and regard this as a quadratic equation in i. Thus we solve
-i^i/2 + (2N-1)i/2 + (1-index) = 0.
We approximate i to be the greatest out of the two resulting solutions (or the ceil of this value, since neglecting j has the effect of lowering the value of i).
We then come back to the complete version of the equation and substitute the approximation of the value of i. If j is outside the interval [1,N-i] we increase/decrease the value of i and re-substitute until we get a value of j in this interval. This loop will probably repeat for a maximum constant number of steps (I suspect a maximum of three steps, but not in the mood to prove it). So this should be doable in a constant number of steps.
As an alternative, we could approximate j to be N/3, instead of zero. This is approximately the expected value of j (over all possible cases), thus the method will probably converge 'faster' at the local search step.
In the general case, you do something very similar, i.e. you solve a fake equation and you perform a local search around the solution.
I found it easier to find i,j from the index in the following number pattern:
0
1 2
3 4 5
6 7 8 9
Since the indices going down the left are the triangular numbers of the form k*(k+1)/2. By solving an appropriate quadratic equation I was able to recover the row and the column from the index. But -- your loops give something like this:
0 1 2 3
4 5 6
7 8
9
which is trickier. It might be possible to solve this problem directly, but note that if you subtract each of these numbers from 9 you get
9 8 7 6
5 4 3
2 1
0
this is the original triangle turned upside down and reflected horizontally. Thus -- I can reduce the problem of your triangle to my triangle. The following Python code shows how it works (the only thing not quite obvious is that in Python 3 // is integer division). The function fromIndexHelper is my solution to my original triangle problem and fromIndex is how I shift it to your triangle. To test it I first printed the index pattern for n = 4 and then the corresponding indices recovered by my function fromIndex:
from math import floor, sqrt
def fromIndexHelper(n,index):
i = floor((-1+sqrt(1+8*index))/2)
j = index - i*(i+1)//2
return i,j
def fromIndex(n,index):
shift = n*(n+1)//2 - 1
i,j = fromIndexHelper(n,shift-index)
return n-i-1,i - j
#test
index = 0
for i in range(4):
for j in range(4-i):
print(index,end = ' ')
index +=1
print('')
print(' ')
index = 0
for i in range(4):
for j in range(4-i):
print(fromIndex(4,index),end = ' ')
index +=1
print('')
Output:
0 1 2 3
4 5 6
7 8
9
(0, 0) (0, 1) (0, 2) (0, 3)
(1, 0) (1, 1) (1, 2)
(2, 0) (2, 1)
(3, 0)