-1

I am working with a text like this one(a .cnf file):

p cnf 5 5

c Thus, this file contains a problem with 5 variables and 5 clauses.

c The following are the clauses for this file:

1 2 3 4 5 0
-1 -2 -3 -4 -5 0
1 -2
3 -4 5 0
5 0
-1 2 0

I need to make a array with the lines that start with numbers, but they must end at the 0 and cut it, so I can generate a array like this:

[
  [1, 2, 3, 4, 5],
  [-1, -2, -3, -4, -5],
  [1, -2, 3, -4, 5],
  [5],
  [-1, 2]
]

I am trying to do this at javascript (working with node.js).

I would be so grateful if someone could help me.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
nosdie
  • 9
  • 2
  • I know that I can separate the text lines using .split('/n') and after cut the lines that start with 'p', 'c', and '', but I dont know how to ignore the /n and make the array split with 0 – nosdie Jun 18 '18 at 19:27

2 Answers2

0

This should do it :

  1. Remove the " 0" at the end of your string
  2. Replace all the "\n" characters with " "
  3. Split your string into an array, using " 0 " as delimiter
  4. Split every element of your character, using " 0 " as delimiter, and convert every element of the array this produces to integer

Demo

const content = `1 2 3 4 5 0
-1 -2 -3 -4 -5 0
1 -2
3 -4 5 0
5 0
-1 2 0`;

const array = content.slice(0, -2)                         // (1)
                     .replace(/\n/g, " ")                  // (2)
                     .split(" 0 ")                         // (3)
                     .map(x => x.split(" ").map(x => +x)); // (4)

console.log(array);
John Slegers
  • 45,213
  • 22
  • 199
  • 169
-1
const data = `1 2 3 4 5 0
-1 -2 -3 -4 -5 0
1 -2
3 -4 5 0
5 0
-1 2 0`;

const result = data
    .split('\n') // create an array of lines
    .map(str => str.split(' ')) // break each line in array
    .filter(([a]) => !isNaN(a)) // filter out those ones that do not start with numbers
    .map(numArr => numArr.filter((item, i, arr) => !(i === (arr.length - 1) && item === '0')).map(Number)); // trim the last item if it is '0'

console.log(result);
Leonid Pyrlia
  • 1,594
  • 2
  • 11
  • 14