Why the line XXX showing an error saying java.lang.ArrayIndexOutOfBoundsException? - multidimensional-array

//Firstly I need to create a 2-D array of floating points(randomly generated) and store them in a text file no of rows and columns are user input
import java.io.;
import java.util.;
public class ClaransS {
public static void main(String args[]) throws IOException {
// *********************************************************************
// Variables declaration n-no.of rows k-forget it for now n_o_d-no. of
// columns
// *********************************************************************
int n, k, n_o_d;
// *********************************************************************
// Creating the text file to store data
// *********************************************************************
File f = new File("C:/x/y/clarans.text");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// *********************************************************************
// Taking user inputs
// *********************************************************************
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Enter the no. of data you want to cluster");
n = userInputScanner.nextInt();
System.out.println(n);
System.out.println("Enter the no. of clusters you want to form");
k = userInputScanner.nextInt();
System.out.println(k);
System.out
.println("Enter the no. of dimensions each data will be in a space of");
n_o_d = userInputScanner.nextInt();
System.out.println(n_o_d);
userInputScanner.close();
// *********************************************************************
// Storing random data in the data-set
// *********************************************************************
double data_set[][] = new double[n][n_o_d];
int count = 1;
int i = 0;
int j = 1;
for (i = 0; i < n; i++) {
data_set[i][0] = count;
for (j = 1; j <= n_o_d; j++) {
//THIS LINE GIVES ERROR
data_set[i][j] = (double) Math.random();//YES THIS ONE XXX
}
count++;
}
for (i = 0; i < n; i++) {
for (j = 0; j <= n_o_d; j++) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.print(data_set[i][j] + "\t");
} catch (IOException e) {
}
}
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.println();
}
}
}
}

The error is in test condition of for
(j = 1; j <= n_o_d; j++).
Test condition will be j < n_o_d

Related

I'm trying to read data from an hash table into a linked list

Im trying to read data from an global hashtable into a linked list. I cant seem to see where I went wrong. Each time I run the program, I get a runtime error.
node *locallinkedlist = NULL;
//Reading Data From the global hashtable into a local linked list to find data using binary search
for(int p = 0; p < 25; p++)
{
for(node *c = hashtable[p]; c != NULL; c = c->next)
{
if(locallinkedlist == NULL)
{
locallinkedlist = c;
}
else
{
c = locallinkedlist;
locallinkedlist = c;
}
}
}
for(node *h = locallinkedlist; h != NULL; h=h->next)
{
printf("%s",h->employeefirstname);
}
I figured it out!
I need to create a node pointer using malloc inside the inner for loop, for each employee and store each of those employee name inside the node pointer and then put it into the list. Heres my revides code!!:
node *head = NULL;
for(int i = 0; i < 25; i++)
{
for(node *j = hashtable[i]; j != NULL; j = j->next)
{
node *m = malloc(sizeof(node));
if(m == NULL)//Checking for a valid memory address
{
return 1;
}
strcpy(m->employeefirstname,j->employeefirstname);
m->next = NULL;
if(head == NULL)
{
head = m;
}
else
{
m->next = head;
head = m;
}
}
}
for(node *c = head; c != NULL; c = c->next)
{
printf("%s\n",c->employeefirstname);
}

Leetcode 2360 Longest Cycle in a Graph

I use nearly the same method as in the discussion. But mine reaches the time limitation but his passes all cases. I want to know how to improve my code and why there is difference?
Here is my entire code:
boolean[] visited;
public int dfs(int step, int[] edges, int node, Map<Integer, Integer> path) {
path.put(node, step);
visited[node] = true;
if (edges[node] == -1) {
return -1;
}
if (path.containsKey(edges[node])) {
return step - path.get(edges[node]) + 1;
}
return dfs(step + 1, edges, edges[node], path);
}
public int longestCycle(int[] edges) {
int res = -1;
visited = new boolean[edges.length];
for (int i = 0; i < edges.length; i++) {
if (visited[i]) {
continue;
}
int maxCircleLength = dfs(0, edges, i, new HashMap<Integer, Integer>());
res = Math.max(maxCircleLength, res);
}
return res;
}
This is his solution:
public int longestCycle(int[] edges) {
int longest = -1;
boolean visited[] = new boolean[edges.length]; // global visisted
HashMap<Integer, Integer> map;
for(int i=0; i<edges.length; i++){
if(visited[i]) continue;
int distance = 0, curr_node = i;
map = new HashMap<>(); // local visited
while(curr_node != -1){
if(map.containsKey(curr_node)){
longest = Math.max(longest, distance - map.get(curr_node));
break;
}
if(visited[curr_node]) break;
visited[curr_node] = true;
map.put(curr_node, distance);
curr_node = edges[curr_node];
distance++;
}
}
return longest;
}

Alternative to System.Web.Security.Membership.GeneratePassword in aspnetcore (netcoreapp1.0)

Is there any alternative to System.Web.Security.Membership.GeneratePassword in AspNetCore (netcoreapp1.0).
The easiest way would be to just use a Guid.NewGuid().ToString("n") which is long enough to be worthy of a password but it's not fully random.
Here's a class/method, based on the source of Membership.GeneratePassword of that works on .NET Core:
public static class Password
{
private static readonly char[] Punctuations = "!##$%^&*()_-+=[{]};:>|./?".ToCharArray();
public static string Generate(int length, int numberOfNonAlphanumericCharacters)
{
if (length < 1 || length > 128)
{
throw new ArgumentException(nameof(length));
}
if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
{
throw new ArgumentException(nameof(numberOfNonAlphanumericCharacters));
}
using (var rng = RandomNumberGenerator.Create())
{
var byteBuffer = new byte[length];
rng.GetBytes(byteBuffer);
var count = 0;
var characterBuffer = new char[length];
for (var iter = 0; iter < length; iter++)
{
var i = byteBuffer[iter] % 87;
if (i < 10)
{
characterBuffer[iter] = (char)('0' + i);
}
else if (i < 36)
{
characterBuffer[iter] = (char)('A' + i - 10);
}
else if (i < 62)
{
characterBuffer[iter] = (char)('a' + i - 36);
}
else
{
characterBuffer[iter] = Punctuations[i - 62];
count++;
}
}
if (count >= numberOfNonAlphanumericCharacters)
{
return new string(characterBuffer);
}
int j;
var rand = new Random();
for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
{
int k;
do
{
k = rand.Next(0, length);
}
while (!char.IsLetterOrDigit(characterBuffer[k]));
characterBuffer[k] = Punctuations[rand.Next(0, Punctuations.Length)];
}
return new string(characterBuffer);
}
}
}
I've omitted the do...while loop over the CrossSiteScriptingValidation.IsDangerousString. You can add that back in yourself if you need it.
You use it like this:
var password = Password.Generate(32, 12);
Also, make sure you reference System.Security.Cryptography.Algorithms.
System.Random doesn't provide enough entropy when used for security reasons.
https://cwe.mitre.org/data/definitions/331.html
Why use the C# class System.Random at all instead of System.Security.Cryptography.RandomNumberGenerator?
Please see the example below for a more secure version of #khellang version
public static class Password
{
private static readonly char[] Punctuations = "!##$%^&*()_-+[{]}:>|/?".ToCharArray();
public static string Generate(int length, int numberOfNonAlphanumericCharacters)
{
if (length < 1 || length > 128)
{
throw new ArgumentException("length");
}
if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
{
throw new ArgumentException("numberOfNonAlphanumericCharacters");
}
using (var rng = RandomNumberGenerator.Create())
{
var byteBuffer = new byte[length];
rng.GetBytes(byteBuffer);
var count = 0;
var characterBuffer = new char[length];
for (var iter = 0; iter < length; iter++)
{
var i = byteBuffer[iter] % 87;
if (i < 10)
{
characterBuffer[iter] = (char)('0' + i);
}
else if (i < 36)
{
characterBuffer[iter] = (char)('A' + i - 10);
}
else if (i < 62)
{
characterBuffer[iter] = (char)('a' + i - 36);
}
else
{
characterBuffer[iter] = Punctuations[GetRandomInt(rng, Punctuations.Length)];
count++;
}
}
if (count >= numberOfNonAlphanumericCharacters)
{
return new string(characterBuffer);
}
int j;
for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
{
int k;
do
{
k = GetRandomInt(rng, length);
}
while (!char.IsLetterOrDigit(characterBuffer[k]));
characterBuffer[k] = Punctuations[GetRandomInt(rng, Punctuations.Length)];
}
return new string(characterBuffer);
}
}
private static int GetRandomInt(RandomNumberGenerator randomGenerator)
{
var buffer = new byte[4];
randomGenerator.GetBytes(buffer);
return BitConverter.ToInt32(buffer);
}
private static int GetRandomInt(RandomNumberGenerator randomGenerator, int maxInput)
{
return Math.Abs(GetRandomInt(randomGenerator) % maxInput);
}
}

Cannot extract more than one metric from Google Analytics Reporting API V4 (Java)

I want to extract more than one Metric from Reporting API V4 Java classes. I pass from "main" function the "ga:" names of dimensions and metrics to the function below:
private static ReportRequest createComplexRequest(java.lang.String startDate,java.lang.String endDate,ArrayList<java.lang.String> metrics,ArrayList<java.lang.String> dimensions, String pageToken){
DateRange dateRange = new DateRange();
dateRange.setStartDate(startDate);
dateRange.setEndDate(endDate);
//Create the Metric object ArrayList
int metricsSize=metrics.size();
Metric[] metricsArray = new Metric[metricsSize];
for(int i=0;i<metricsSize;i++){
Metric metric = new Metric()
.setExpression("ga:"+metrics.get(i))
.setAlias(metrics.get(i));
metricsArray[i]=metric;
}
int dimensionsSize=dimensions.size();
Dimension[] dimensionsArray = new Dimension[dimensionsSize];
for(int i=0;i<dimensionsSize;i++){
Dimension dimension = new Dimension()
.setName("ga:"+dimensions.get(i));
dimensionsArray[i]=dimension;
}
ReportRequest request = new ReportRequest()
.setViewId(VIEW_ID)
.setDateRanges(Arrays.asList(dateRange))
.setDimensions(Arrays.asList(dimensionsArray))
.setMetrics(Arrays.asList(metricsArray))
.setPageToken(pageToken)
.setPageSize(10000);
return request;
}
As an example, I'm trying to extract "sessions" and "bounces" metrics. While I was trying to troubleshoot this case I realized that the metricHeaders.size() is 2 (as many as my metrics) but row.getMetrics() returns only one ("session" metric). Below is what I mean. I intentionally created the following problematic print function which reveals the problem:
private static void printResponse(GetReportsResponse response) {
for (Report report: response.getReports()) {
ColumnHeader header = report.getColumnHeader();
List<String> dimensionHeaders = header.getDimensions();
List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
List<ReportRow> rows = report.getData().getRows();
if (rows == null) {
System.out.println("No data found for " + VIEW_ID);
return;
}
for (ReportRow row: rows) {
List<String> dimensions = row.getDimensions();
List<DateRangeValues> metrics = row.getMetrics();
System.out.println("Metrics size:"+metrics.size());
for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
}
for(int l = 0;l<metricHeaders.size();l++)
{
System.out.println(metricHeaders.get(l).getName());
DateRangeValues values = metrics.get(l);
}
}
}
}
The above function crushes because metricHeaders.size() is 2 but metrics is List with only one metric, the "sessions" metric!! That's why I get:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
Do you have any idea why this happens??? Please help!!
The sample printResponse() method in GA developers guide has some errors.
Try the following code instead:
private static void printResponseCustom(GetReportsResponse response) {
for (Report report: response.getReports()) {
ColumnHeader header = report.getColumnHeader();
List<String> dimensionHeaders = header.getDimensions();
List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
List<ReportRow> rows = report.getData().getRows();
if (rows == null) {
System.out.println("No data found for " + VIEW_ID);
return;
}
for (ReportRow row: rows) {
List<String> dimensions = row.getDimensions();
List<DateRangeValues> metrics = row.getMetrics();
System.out.println("Metrics size:"+metrics.size());
System.out.println("Metrics headers:"+metricHeaders.size());
for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
}
int k = 0;
for (int j = 0; j < metricHeaders.size() && j < metrics.size();
DateRangeValues values = metrics.get(j);
for (String value : values.getValues()) {
MetricHeaderEntry entry = metricHeaders.get(k);
System.out.println(entry.getName() + ": " + value);
k++;
}
}
}
}
}

Read text file saved in SD card line by line

I have data.txt file saved in SD card containing values of variables required for driving 3 stepper motors. I want to read data.txt file line by line, split the line by "," and save each values into respective variables. data.txt file has data something like this:
8.24, 5.67, 7.34
3,86, 3.56, 4.49
5.38, 6.29, 3.67
I want to save value of first integer in x, second in y and third in z and execute the code. Once the code is executed, I want to get next line and load respective values in their respective variables and continue the loop till there is no line left in data.txt file
This code for matrix, let change some type that you need
public Matrix loadIntMapData(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
ArrayList<double[]> list = new ArrayList<double[]>();
while ((line = reader.readLine()) != null) {
if (line.equals("")) {
//ignore
} else {
String[] vs = line.split(",");
double ints[] = new double[vs.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = Double.parseDouble(vs[i]);
}
list.add(ints);
}
}
double[][] map = new double[list.size()][];
for (int i = 0; i < map.length; i++) {
map[i] = list.get(i);
}
return new Matrix(map);
}
public static final void writInteMapData(Matrix matrix, File file) throws IOException {
double[][] map = matrix.getArray();
StringBuffer output = new StringBuffer();
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
output.append(Double.toString(map[i][j]));
if (j != map[i].length - 1) {
output.append(",");
}
}
if (i != map.length - 1) {
output.append("\r\n");
}
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(output.toString());
writer.close();
}

Resources