0

I have several Figure objects stored in an array called figureTab, and I'm storing used elements in an array called used.

Do I need to set a random number twice? Objects inside the array

var used = [];
for (let i = 0; i < figureTab.length; i++) {
  var random = Math.floor(Math.random() * figureTab.length);


  if (used.length == 0) {
      used.push(random);
      html += "<div>" + (figureTab[random].FigureNr + 1) + "></div>"
  }
  else{
      for (let j = 0; j < used.length; j++) {
          if (used[j] == random) {
              random = Math.floor(Math.random() * figurTab.length);
              j = 0;
          }
       }    
       used.push(random);
       html += "<div>" + (figureTab[random].FigureNr + 1) + "></div>";
   }


document.getElementById("alternatives").innerHTML = html;
3
  • 1
    Could you please give a proper example with your question? Say sample input and the output of the input? Commented May 5, 2020 at 20:06
  • WTH is this: .FigureNr ? Commented May 5, 2020 at 20:12
  • I'm printing figures, and finding the image-path in the figures tab. Input: [1,2,3,4,5] Output: [3,2,5,1,4]. They're shuffled and only used once. See the image, and maybe you'll understand. I'm basicly outputting five figures randomly, and once from that figureTab. Commented May 5, 2020 at 20:18

2 Answers 2

1

If what you're looking for is array shuffler, there's a much shorter way to do that (implementing Fisher-Yates algorithm), using Array.prototype.reduceRight():

const src = [{id:0, name: 'circle', path:'data:image/svg+xml;base64, PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCiAgPGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNTAiLz4NCjwvc3ZnPg=='}, {id:1, name: 'triangle', path: 'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik0wLDAgaDEwMCB2MTAwIHoiLz4NCjwvc3ZnPg=='}, {id:2, name: 'rhombus', path:'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik01MCwwIGw1MCw1MCBsLTUwLDUwIGwtNTAtNTAgeiIvPg0KPC9zdmc+'}, {id:3, name: 'square', path: 'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik0wLDAgaDEwMCB2MTAwIGgtMTAwIHoiLz4NCjwvc3ZnPg=='}, {id:4, name: 'trapezoid', path:'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCsKgIDxwYXRoIGQ9Ik0wLDEwMCBoMTAwIGwtMjAsLTEwMCBoLTYwIHoiLz4NCjwvc3ZnPg=='}],
      wrapper = document.getElementById('wrapper'),

      shuffle = arr => arr.reduceRight((r,_,__,s) => 
        (r.push(s.splice(0|Math.random()*s.length,1)[0]), r),[])

shuffle(src).forEach(({name,path}) => {
  const figure = document.createElement('img')
  figure.src = path
  figure.alt = name
  wrapper.appendChild(figure)
})
img{
  width: 100px;
  height:100px;
  margin: 10px;
}
<div id="wrapper"></div>

Sign up to request clarification or add additional context in comments.

4 Comments

How can I translate that into HTML, and into what I'm trying to do? Maybe rough question, I guess I need an array shuffler, but I also need to print the images - and the path to those images are stored in the array.
@ErikSkjellevik : would you describe your use case in a bit more details, so that I may adjust my answer to fulfil necessary requirements?
Unsure about the syntax, but I'll try. I have objects inside one array. figureTab = [Figure { FigureNumber: 0, Name: "Circle", Path: "/images/circle.png"}] And so on. Next figure might be a triangle, with FigureNumber: 1 and Path: "/images/triangle.png"... What I need to is to print all the figures in this array, once, and in random order. See image (in Norwegian) i.sstatic.net/AiS5f.png
Maybe this is what I need. But the main issue is that i need the path, and I think only the path. Then I'll use a for loop (?) to print all the figures with different paths. Example output: <img src="/images/circle.png"> <img src="/images/square.png"> and so on
0

There are two functions:

/*
- Shuffles an array properly -- without duplicates -- based on the Fischer-Yeats 
  algorithm
*/
shuffle(array)

/*
- Passes an htmlString, an array, and an optional selector of the tag that the new
  HTML will be rendered into (if no selector is provided then it will render to 
  <body> by default).
*/
function renderString(string, shuffled, selector = 'body')

function renderString(string, shuffled, selector = 'body') {
  const node = document.querySelector(selector);
  for (let [index, url] of shuffled) {
    node.insertAdjacentHTML('beforeend', string);
    node.lastElementChild.firstElementChild.src += url;
    node.lastElementChild.lastElementChild.textContent = index;
  }
}

function shuffle(array) {
  let qty = array.length,
    temp, i;
  while (qty) {
    i = Math.floor(Math.random() * qty--);
    temp = array[qty];
    array[qty] = array[i];
    array[i] = temp;
  }
  return array;
}

const thumbs = [[0, '/img/link.gif'], [1, '/img/sol.png'], [2, '/img/ren.gif'], [3, '/img/balls.gif'], [4, '/img/austin.gif']];

const htmlString = `
<figure>
  <img src='https://glpjt.s3.amazonaws.com/so/av'>
  <figcaption></figcaption>
</figure>`;
let mixed = shuffle(thumbs);
//console.log(mixed);

renderString(htmlString, mixed, 'main');
main {
  display: flex;
  flex-flow: column nowrap;
  justify-content: start;
  width: 80%;
  margin: 0 auto;
}

figure {
  width: 320px;
  margin: 0 auto;
  padding: 5px 10px;
  outline: 3px outset tomato;
  font-family: Verdana;
  font-size: 3rem;
}

img {
  display: block;
  max-width: 100%;
  height: auto;
  object-fit: contain;
}

figcaption {
  text-align: center;
}
<main></main>

3 Comments

Well this is something. I think I'm too noob for this. Please see my comment on the other answer to maybe get a better understanding of what I'm trying to do. Or maybe you've given the answer, but I'm just a student haha rip
Ah maybe I did not iterate clearly, but I have pictures of the figures. PNGs in an Images folder. The object has a key Path and a value for example /Images/Circle.png. Therefore I cannot just print out integers.
See update, you need to provide the actual code in text form of object not a pic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.